This is for Python 2.7 ....
I have a Django project, and I use logging.config.dictConfig(CONFIG) to get the logging that I want when running the Django app as a server. I have my own module in mycore.logging, and it creates a logger object at import-time. This is all great.
However, Django has independent 'management commands' and I want to log each management command to its own separate file. The logfile name would be the name of the management command + ".log".
I've searched and googled and not found any examples of this. Is it really so unusual? Or have I just not found the prior art?
I think I know how to remove the existing FileHandler, instantiate a new one with my desired output file, and add it as a handler on the logger object.
But it seems like a clunky thing to do. Any advice will be welcome.
import logging
import logging.config
from logutils.colorize import ColorizingStreamHandler
from django.conf import settings
class ColorHandler(ColorizingStreamHandler):
def __init__(self, *args, **kwargs):
super(ColorHandler, self).__init__(*args, **kwargs)
self.level_map = {
# Provide your custom coloring information here
logging.DEBUG: (None, 'blue', False),
logging.INFO: (None, 'green', False),
logging.WARNING: (None, 'yellow', False),
logging.ERROR: (None, 'red', False),
logging.CRITICAL: ('red', 'white', True),
}
try:
CONSOLE_LOG_LEVEL = settings.CONSOLE_LOG_LEVEL
except AttributeError as ae:
CONSOLE_LOG_LEVEL = logging.INFO
try:
FILE_LOG_LEVEL = settings.FILE_LOG_LEVEL
except AttributeError as ae:
FILE_LOG_LEVEL = logging.DEBUG
CONFIG = {
'version':1,
'disable_existing_loggers': True,
'handlers':{
'console': {
'()':ColorHandler,
'level': CONSOLE_LOG_LEVEL,
'formatter': 'simplest',
'stream': 'ext://sys.stdout',
},
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'level': FILE_LOG_LEVEL,
'formatter': 'simplest',
'filename': './log-oxfam.txt',
'mode': 'a',
'maxBytes': 10485760,
'backupCount': 5,
},
},
'formatters': {
'simplest': {
'format': '%(levelname)-8s %(message)s',
},
'time_level_message': {
'format': '%(asctime)s %(levelname)-8s %(message)s',
},
'detailed': {
'format': '%(asctime)s %(module)s line:%(lineno)-4d %(levelname)-8s %(message)s',
},
},
'loggers': {
'myDjangoApp': {
'level':'DEBUG',
'handlers':['console', 'file'],
###'handlers':['console'],
},
},
}
logging.config.dictConfig(CONFIG)
logger = logging.getLogger("myDjangoApp")