def _getCallerLogger():
caller = inspect.currentframe().f_back.f_back
name = "{}-{}".format(caller.f_globals['__name__'], caller.f_code.co_name )
logger = logging.getLogger(name)
return logger
log = lambda msg : _getCallerLogger().debug(msg)
info = lambda msg: _getCallerLogger().info(msg)
warning = lambda msg: _getCallerLogger().warning(msg)
error = lambda msg: _getCallerLogger().error(msg)
critical = lambda msg: _getCallerLogger().critical(msg)
I have the above logging code in my application so I can just call log
from anywhere and it will print the file and where the log method was called from.
Would there be anything wrong with this in the long run?
1 Answer 1
The logging module already supplies a function name to log messages. If you want to include the function name in your log message just set the appropriate formatter with %(funcName)s
in the format string on your log handler with: http://docs.python.org/2/library/logging.html#logging.Handler.setFormatter
See also http://docs.python.org/2/library/logging.html#logrecord-attributes
The typical usage is to create a global log
variable in your module like
logger = logging.getLogger(__name__)
and use that logger within functions in that module. But creating a separate logger for every single function is excessive.
I (just now) realized this is a pretty old question, but if you're still interested I can provide a full working example.
log = _getCallerLogger().debug
? why dont' you set the logger in a variable instead of creating a new one 5 times? \$\endgroup\$