I'm using Pythons logging
module. I want to log the full path of a message, like
"msg packagename.modulename.functionName lineNumber", but how can I get the package name of a message?
The logging configuration is:
LOGGING = {
'formatters': {
'simple': {
'format': '[%(levelname)s] %(message)s [%(module)s %(funcName)s %(lineno)d]'
},
},
'handlers': {
'console': {
'level':'INFO',
'class':'logging.StreamHandler',
'formatter':'simple',
}
},
'loggers': {
'develop': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
}
}
and I get a logger like this:
logger = logging.getLogger('develop')
I see two solutions to the problem.
One, pass in the filename with every call to log.[debug,info,error,...] as obtained by the __file__
magic variable. This does not give you the package name, but it's as good as that for finding out where the log message originated. The downside is that you'd need to modify every logging call in your application.
Two, make a subclass of logging.Logger
which overrides the Logger.log
instance method. In your new log
method, use the inspect.stack()
and inspect.getframeinfo()
methods to find the stack frame which caused the call to log
in your code and extract filename and line numbers. You can then modify the log message which was passed in accordingly. Finally, tell the logging
module to use your subclass by calling logging.setLoggerClass()
.