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.Loggerwhich overrides theLogger.loginstance method. In your newlogmethod, use theinspect.stack()andinspect.getframeinfo()methods to find the stack frame which caused the call tologin your code and extract filename and line numbers. You can then modify the log message which was passed in accordingly. Finally, tell theloggingmodule to use your subclass by callinglogging.setLoggerClass().