Home > Mobile >  Avoid showing logger entries in console
Avoid showing logger entries in console

Time:12-29

I have one "basic" logging configuration that logs to stdout in my project.

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"

logging.basicConfig(
    level=logging.INFO,
    format=SERVER_FORMAT,
    datefmt=DATETIME_FORMAT,
    handlers=[stream_handler])

I have also another logger user_logger that should not print anything. Instead, it should store log entries in a variable.

user_logger = logging.getLogger('user_logger')
user_logger.setLevel(logging.INFO)

log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)

log_capture_string_handler.setFormatter(logging.Formatter(USER_FORMAT))
user_logger.handlers = [log_capture_string_handler]

The problem is that when I call:

user_logger.info('This should only be in "log_capture_string"')

it prints it to the console.

Do you know how to avoid that?

CodePudding user response:

You should set user_logger.propagate = False. logging.propagate docs

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

So, your root logger will not send any data to stderr.

This example outputs nothing

import io
import logging

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"

logging.basicConfig(
    level=logging.INFO,
    format=SERVER_FORMAT,
    datefmt=DATETIME_FORMAT,
    handlers=[stream_handler])

user_logger = logging.getLogger('user_logger')
user_logger.propagate = False
user_logger.setLevel(logging.INFO)

log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)

log_capture_string_handler.setFormatter(logging.Formatter(SERVER_FORMAT))
user_logger.handlers = [log_capture_string_handler]

user_logger.info('This should only be in "log_capture_string"')
  • Related