What is the DRY way of setting different places in the log files for different settings?

I am using the python logging module in a django project. I am doing the basic logging configuration in my settings.py file. Something like that:

 import logging import logging.handlers logger = logging.getLogger('project_logger') logger.setLevel(logging.INFO) LOG_FILENAME = '/path/to/log/file/in/development/environment' handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) 

I have a separate settings file for production. This file ( production.py ) imports everything from settings and overrides some parameters (for example, DEBUG to False ). I want to use another LOG_FILENAME for production. How can I do it? I can repeat the entire configuration section in production.py , but this creates problems if /path/to/log/file/in/development/environment not in the working machine. In addition, he does not look too “DRY”.

Can anyone suggest a better way to do this?

+4
source share
2 answers

Found a reasonable “DRY” solution that worked. Thanks Writing in Python in Django

Now I have log.py that looks something like this:

 import logging, logging.handlers from django.conf import settings LOGGING_INITIATED = False LOGGER_NAME = 'project_logger' def init_logging(): logger = logging.getLogger(LOGGER_NAME) logger.setLevel(logging.INFO) handler = logging.handlers.TimedRotatingFileHandler(settings.LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) if not LOGGING_INITIATED: LOGGING_INITIATED = True init_logging() 

My settings.py now contains

 LOG_FILENAME = '/path/to/log/file/in/development/environment 

and production.py contains:

 from settings import * LOG_FILENAME = '/path/to/log/file/in/production/environment' 
+1
source

Why don't you put these instructions at the end of settings.py and use the flas es DEBUG indicator for development?

Something like that:

 import logging import logging.handlers logger = logging.getLogger('project_logger') logger.setLevel(logging.INFO) [snip] if DEBUG: LOG_FILENAME = '/path/to/log/file/in/development/environment' else: LOG_FILENAME = '/path/to/log/file/in/production/environment' handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) 
+1
source

All Articles