I would like to have a logger that can be used both in django and in celery.
When used by django it should print to console, while when used from a celery task, I would like it to output using the default celery handler (in my case, it dumps to a file specified by the –logfile cmd line argument).
This is especially useful for helper functions that are used by both the django server and celery tasks.
This is what I have in my settings.py
file:
LOGLEVEL = os.environ.get("LOGLEVEL", "info").upper()
LOGGING = {
"version": 1, # the dictConfig format version
"disable_existing_loggers": False, # retain the default loggers
"handlers": {
# console logs to stderr
"console": {
"class": "logging.StreamHandler",
"formatter": "verbose",
},
"django.server": DEFAULT_LOGGING["handlers"]["django.server"],
},
"formatters": {
"verbose": {
"format": "[{asctime}]|{levelname}| {message}",
"style": "{",
},
"django.server": {
# "()": "django.utils.log.ServerFormatter",
"format": "[{asctime}]|{levelname}| {message}",
"style": "{",
},
},
"loggers": {
# default for all undefined Python modules
"": {
"level": "WARNING",
"handlers": ["console"],
},
# Our application code
"app": {
"level": LOGLEVEL,
"handlers": ["console"],
# Avoid double logging because of root logger
"propagate": False,
},
# Default runserver request logging
"django.server": DEFAULT_LOGGING["loggers"]["django.server"],
"django.channels.server": DEFAULT_LOGGING["loggers"]["django.server"],
},
}
In my “app” logger, I have only the console handler for now.
If I define a logger like this:
logger = get_task_logger("app").getChild(__name__)
The output goes to the console, but not to the logfile.
If I define a logger like this instead:
logger = get_task_logger(__name__)
The output goes to the logfile, but not to the console.
I would like, somehow, to add the default celery handler, which I think is created/setup here, to my “app” logger.
Is this possible?