0

I want to log to stream of io.StringIO, but end up with empty stream. Here is my code:

import logging, io

log_handler = logging.StreamHandler(stream)
log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
log_handler.setFormatter(log_format)
log_handler.setLevel(logging.INFO)

logger.addHandler(log_handler)

logger.info("This is test info log")
print(stream.getvalue())

What am I doing wrong?

UPDATE It seems to be working if I replace level with "Warning" like this

log_handler.setLevel(logging.WARNING)
logger.warning("This is test info log")

It also prints into console for some reason

user1700890
  • 7,144
  • 18
  • 87
  • 183
  • this may help you https://stackoverflow.com/questions/9534245/python-logging-to-stringio-handler – sahasrara62 Jan 06 '23 at 18:35
  • Apparently, I needed `logger.setLevel(logging.INFO)`. One can set level on logger and handler separately. Here is the link: https://docs.python.org/3.8/howto/logging.html#logging-advanced-tutorial – user1700890 Jan 06 '23 at 18:39
  • Here is useful discussion: https://stackoverflow.com/questions/6614078/logging-setlevel-how-it-works – user1700890 Jan 06 '23 at 18:39

1 Answers1

1

Configure the root logger: logging.basicConfig(level=logging.DEBUG).

Then you can set log_handler.setLevel(logging.INFO) to whatever level you wish, it will capture logs to stream accordingly.