I'd like to be able to do simple and consistent logging in my code using the Python logging facility.
I am able to do the following:
- I'd like all existing/future module and functions to have "Entering ..." and "Done ..." log messages.
- I don't want to add the same code snippet to defining logging parameters (shown below
don't want to add everywhere
) in every function definition. - I want the
log.info(...)
etc constructs to work in any function I define in the project hierarchy.
What doesn't work / I don't know how to do it:
- I'd like to avoid defining the same
@log
decorator in every existing/new module that I write.
# don't want to add everywhere
FORMAT = '%(asctime)s - %(name)-20s - %(levelname)-5s - %(message)s'
LEVEL = logging.DEBUG
logging.basicConfig(format=FORMAT, level=LEVEL)
log = logging.getLogger(__name__)
**Sample code from my Flask project:**
# app/__init__.py
from a import b # various other imports required for app
import logging
FORMAT = '%(asctime)s - %(name)-20s - %(levelname)-5s - %(message)s'
LEVEL = logging.DEBUG
logging.basicConfig(format=FORMAT, level=LEVEL)
log = logging.getLogger(__name__)
# ... various other app init code
from app import views, models
#app/views.py
from c import d # various other imports required for the module
def logger(fn):
from functools import wraps
import inspect
@wraps(fn)
def wrapper(*args, **kwargs):
global log
log = logging.getLogger(inspect.stack()[1][3])
log.info('About to run %s' % fn.__name__)
out = fn(*args, **kwargs)
log.info('Done running %s' % fn.__name__)
# Return the return value
return out
return wrapper
@app.route('/this_func')
@logger
def this_func():
log.info('I am doing logging without having to do bunch of definitions.')
# some more code
@app.route('/that_func')
@logger
def that_func():
log.info('Yet more logging without having to do bunch of definitions.')
log.info('I can simply refer to the log object and be done with it.')
# some more code