It'd be useful if the code that configures a lambda-friendly logger was in a standalone function so it could be used by code in chalicelib that doesn't need a dependency on a chalice app.
Is there a reason you can't use the app's logger or the root logger (which is already configured by lambda for you)?
The function I'm calling doesn't need any dependency on the app itself. It's in a package inside chalicelib, so it seems odd to create a dependency on passing in a logger from the app. I'll copy the code from the Chalice class to configure my own logger, but if there was a function to set up and configure a logger Chalice could use, and so could code like mine without repeating myself.
This does the trick:
import logging
import sys
def get_logger(name, level=logging.ERROR,
format='%(name)s - %(levelname)s - %(message)s'):
"""
Gets a logger with the given name configured for lambda
:param name: Name of the logger to retrieve
:param level: Logging level to configure the logger for, either as a
`logging` constant (e.g. `logger.DEBUG`) or a case-insensitive string
corresponding to one of the logging constants, (e.g. `"debug"`).
:param format: Log formatting string
:return: Logger
"""
handler = logging.StreamHandler(sys.stdout)
# Timestamp is handled by lambda itself so the
# default FORMAT_STRING doesn't need to include it.
formatter = logging.Formatter(format)
handler.setFormatter(formatter)
log = logging.getLogger(name)
log.propagate = False
log.addHandler(handler)
if type(level) == str:
level = getattr(logging, level.upper())
log.setLevel(level)
return log
BTW @stealthycoin how can I get access to the current app's logger inside a module inside chalicelib?
I didn't find a method like Flask's current_app
I was thinking of explicitly passing it. Something like this:
from chalice import Chalice
from chalicelib.thing import ThingInterface
app = Chalice(name='test')
thing_interface = ThingInterface(logger=app.log)
@app.route('/thing/{thing_id}')
def get_thing(thing_id):
thing = thing_interface.get_thing(thing_id)
return {
'thing': thing.to_dict()
}
@stealthycoin it makes sense, but I still thinking that the feature requests is valid. Thanks
Using this line in each module did the trick for me
logger = logging.getLogger('app')
Most helpful comment
@stealthycoin it makes sense, but I still thinking that the feature requests is valid. Thanks