Search code examples
pythonpython-2.7loggingfilehandler

logger configuration to log to file


Python newbie. Now I have been stuck around this for a while. When I try to write logs in a file using ini configuration nothing is captured in the file. I tried to debug the problem but couldn't get any clue. Writing logs without using ini file works perfectly fine.

Below is the code and ini file

import logging

from logging.config import fileConfig

def info(message):


    fileConfig('logging_config.ini')
    logger=logging.getLogger("simple logger")

    logger.warning('Something is not right')
    logger.warning(message)

logging_config.ini

[loggers]
keys=root

[handlers]
keys=file_handler

[logger_root]
level=WARNING
handlers=file_handler

[formatters]
keys=formatter

[formatter_formatter]
format='%(message)s'

[handler_file_handler]
class=FileHandler
level=WARNING
formatter=formatter
args=('dummyoutput.log','w')

I checked the logger object also to see if I can get any clue from its properties. Below is the object

{'disabled': 0,
 'filters': [],
 'handlers': [<logging.FileHandler object at 0x7ff03358ce90>],
 'level': 30,
 'name': 'root',
 'parent': None,
 'propagate': 1}

Not sure if its helpful but I noticed the property disabled was earlier shown TRUE but now it is 0 every time.

Has anyone got any clue on this?

Update: The issue was due to multiple calls to logging.config.fileConfig() for the same configuration file. But I couldn't really understand why nothing was written when that function was called for the last time. Any idea on that??


Solution

  • Figured out what the (stupid) mistake was. Actually the info(message) was getting called more than once and so was fileConfig() for the same configuration file as it was inside info function. Hence, the issue. Modified code as below and it worked.

    import logging
    from logging.config import fileConfig
    
    def info(message):
    
        logger.warning('Something is not right')
        logger.warning(message)
    
    fileConfig('logging_config.ini')
    logger=logging.getLogger("simple.logger")
    

    Update: Even if we don't follow the logger naming convention for eg. as I gave simple logger instead of simple.logger it works fine.