Search code examples
pythonpython-3.xloggingerror-logging

Logging in Python console and in log file


I'm using the logging library and would like to log on to the console and store those logs in a file.

        logger = logging.getLogger(module)
        handler = logging.StreamHandler()
        
        formatter = logging.Formatter(
            '%(asctime)s [%(name)s] %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)
        filehandler=logging.FileHandler('logfile.log')
        logger.addHandler(filehandler)
        logger.info('hello')

my goal is to see logs in the below format.

[time]  [module]  [info/error]  [log-msg]

I'm getting this format in the console but in log file I'm getting only log-msg


Solution

  • filehandler.setFormatter(formatter)