Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using dictConfig in python logging, need to create a logger with a different file than defined in dict.

Tags:

python

logging

I have a LOG_SETTINGS dict that looks like:

LOG_SETTINGS = {
'version': 1,
'handlers': {
    'console': {
        'class': 'logging.StreamHandler',
        'level': 'INFO',
        'formatter': 'detailed',
        'stream': 'ext://sys.stdout',
    },
    'file': {
        'class': 'logging.handlers.RotatingFileHandler',
        'level': 'INFO',
        'formatter': 'detailed',
        'filename': '/tmp/junk.log',
        'mode': 'a',
        'maxBytes': 10485760,
        'backupCount': 5,
    },

},
'formatters': {
    'detailed': {
        'format': '%(asctime)s %(module)-17s line:%(lineno)-4d ' \
        '%(levelname)-8s %(message)s',
    },
    'email': {
        'format': 'Timestamp: %(asctime)s\nModule: %(module)s\n' \
        'Line: %(lineno)d\nMessage: %(message)s',
    },
},
'loggers': {
    'extensive': {
        'level':'DEBUG',
        'handlers': ['file',]
        },
}
}

In my code I do the following:

logging.config.dictConfig(LOG_SETTINGS)

logger = logging.getLogger('extensive')
logger.info("This is from Runner {0}".format(self.default_name))

logger2 = logging.getLogger('extensive')
logfile = logging.FileHandler("test.log")
logger2.addHandler(logfile)

logger2.info("This is from Runner {0} to the new   file.".format(self.default_name))

But the output is still written to the original log file defined in LOG_SETTINGS. What I am looking for is to have the ability to say: logger2.replaceHandler(logfile) rather than addHandler.

Is there a way to do this?

like image 883
John Avatar asked Jun 07 '12 12:06

John


People also ask

What is dictConfig Python?

If you want to send configurations to the listener which don't disable existing loggers, you will need to use a JSON format for the configuration, which will use dictConfig() for configuration. This method allows you to specify disable_existing_loggers as False in the configuration you send.

How does logger work in Python?

Logging LevelsWhen you set a logging level in Python using the standard module, you're telling the library you want to handle all events from that level on up. If you set the log level to INFO, it will include INFO, WARNING, ERROR, and CRITICAL messages. NOTSET and DEBUG messages will not be included here.


1 Answers

firstly, empty your logger handlers logger.handlers = [] then add another handler.

logger2 = logging.getLogger('extensive')
logfile = logging.FileHandler("test.log")
logger2.handlers = []
logger2.addHandler(logfile)
like image 173
iMom0 Avatar answered Oct 13 '22 11:10

iMom0