0

I am able to store error logs to a file... but not info() or any other Logging Levels.

What am I doing wrong?

How can I store any level of logs to FileHandler?


code.py

import sys
import logging

def setup_logging():
    global logger
    logger = logging.getLogger()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    open('data_module.log', 'w').close()  # empty logs
    global fileHandler
    fileHandler = logging.FileHandler('data_module.log')
    fileHandler.setFormatter(formatter)
    fileHandler.setLevel(logging.DEBUG)
    logger.addHandler(fileHandler)
    logger.error('Started')  # info
    logger.info('information')  # info

test.py:

import code as c

c.setup_logging()

with open('data_module.log', 'r') as fileHandler:
    logs = [l.rstrip() for l in fileHandler.readlines()]
open('data_module.log', 'w').close()  # empty logs

assert len(logs) == 2

Error:

AssertionError: assert 1 == 2

Please let me know if there's anything else I should add to post.

StressedBoi69420
  • 1,376
  • 1
  • 12
  • 40

1 Answers1

1

You need to set the level for the logger itself:

logger.setLevel(logging.DEBUG)

The default log level is WARN: when you write a DEBUG-level message, the logger does not handle it (ie send it to a handler). The handler you added is never invoked.

The handler can have its own level, but that is consulted only after the handler is invoked. If a logger sends a DEBUG message to a handler that is only interested in INFO+ messages, it does nothing.

kielni
  • 4,779
  • 24
  • 21