19

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?

1 Answer 1

15

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Another thing I found is the removeHandler link, but I'm not sure what the 'hdlr' is? .
for handler,it is a logging handler object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.