I have a django app with two management commands, which both call a common library. Lets call them sync_a and sync_b. I want the log entry to record the calling function (or module), so that I know if the log message comes from sync_a or sync_b
# sync_a.py
from utils.some_module import some_function
import logging
logger = logging.getLogger(__name__)
class Command(BaseCommand):
some_function('a')
# sync_b.py
from utils.some_module import some_function
import logging
logger = logging.getLogger(__name__)
class Command(BaseCommand):
some_function('a')
# some_module.py
def some_function(param):
logger.info("running")
My logging settings in settings.py are:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'semi_verbose': {
'format': '[%(levelname)s] %(module)s %(name)s %(funcName)s(): %(message)s'
},
},
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'semi_verbose'
}
},
'loggers': {
'app': {
'handlers': ['console'],
'level': 'debug',
'propagate': True
}
}
}
The log messages I’m seeing are of the format:
[INFO] utils.some_module some_function(): running
I’d like them to include either sync_a or sync_b.
I’m not sure if what I’m trying to do is unusual or if I’ve configured things incorrectly. I know that I could customise the log.info() line to use the parameter or to use inspect, but I’m trying to find a solution that works without needing to do this because I have several management commands and libraries that I’d like it to work across.
I took a look at the Python logging documentation, and it doesn’t look like the
LogRecordcaptures the information you’re looking for.If I were going to do this, I think I would write a custom
Formatterthat could look up and add call stack information to the logging call. The inspect module’s stack function is probably the best way to do that.