Question

I have create a global logger using the following:

def logini():
    logfile='/var/log/cs_status.log'
    import logging
    import logging.handlers
    global logger
    logger = logging.getLogger()
    logging.basicConfig(filename=logfile,filemode='a',format='%(asctime)s %(name)s %(levelname)s %(message)s',datefmt='%y%m%d-%H:%M:%S',level=logging.DEBUG,propagate=0)
    handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=2000000, backupCount=5)
    logger.addHandler(handler)  
    __builtins__.logger = logger

It works, however I am getting 2 outputs for every log, one with the formatting and one without.

I realize that this is being caused by the file rotater as I can comment out the 2 lines of the handler code and then I get a single outputted correct log entry.

How can I prevent the log rotator from outputting a second entry ?

Was it helpful?

Solution

Currently you're configuring two file loggers that point to the same logfile. To only use the RotatingFileHandler, get rid of the basicConfig call:

logger = logging.getLogger()
handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=2000000,
                                               backupCount=5)
formatter = logging.Formatter(fmt='%(asctime)s %(name)s %(levelname)s %(message)s',
                              datefmt='%y%m%d-%H:%M:%S')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)  

All basicConfig does for you is to provide an easy way to instantiate either a StreamHandler (default) or a FileHandler and set its loglevel and formats (see the docs for more information). If you need a handler other than these two, you should instantiate and configure it yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top