1

I'm just starting to learn how to use structlog and I'm having a difficult time trying to figure out how to turn off colored logging when it writes to files. Essentially what I did was take my old code that I had used with the standard logging module and converted it to work with structlog - this is what I came up with:

formatter = logging.Formatter(
    fmt=LOGGER_OUTPUT_FORMAT,
    datefmt=LOGGER_DATETIME_FORMAT,
    )
handler = logging.StreamHandler()
handler.setLevel(level)
handler.setFormatter(formatter)
logger.addHandler(handler)

# create a file handler
formatter = logging.Formatter(
    fmt=LOGGER_OUTPUT_FORMAT,
    datefmt=LOGGER_DATETIME_FORMAT,
    )
handler = RotatingFileHandler(
    filename=LOGFILE_PATH,
    maxBytes=4000000,
    backupCount=20,
    )
handler.setLevel(level)
handler.setFormatter(formatter)
logger.addHandler(handler)

structlog.configure(logger_factory=LoggerFactory())
logger = structlog.getLogger('output_logger')

What I can't figure out how to do is where to insert lines to change the formatter such that it doesn't use colored output when saving the logging output to a file. I'm guessing I can uninstall colorama, but that seems like it would be defeating the purpose of actually learning how to use structlog. I've dug through the structlog manual but it's just not making sense to me, and everything I seem to try throws errors, so any guidance would be much appreciated!

Mike
  • 504
  • 7
  • 23

1 Answers1

1

Depending on what you want to achieve exactly, you'll have to add more configuration to structlog.configure.

If you want stdlib logging and structlog to cooperate, check out https://www.structlog.org/en/stable/standard-library.html


If you just want to use structlog's native loggers without colors, you only have to adapt your processors for now.

As the Getting Started tutorial says, the default is

[
    structlog.processors.StackInfoRenderer(),
    structlog.dev.set_exc_info,
    structlog.processors.format_exc_info,
    structlog.processors.TimeStamper(),
    structlog.dev.ConsoleRenderer()
]

Which is colorful if colorama is present. The simplest change would be changing it to

[
    structlog.processors.StackInfoRenderer(),
    structlog.dev.set_exc_info,
    structlog.processors.format_exc_info,
    structlog.processors.TimeStamper(),
    structlog.dev.ConsoleRenderer(colors=False)
]

although production code should probably use structlog.processors.KeyValueRenderer or structlog.processors.JSONRenderer since ConsoleRenderer is optimized for human consumption in a…console. :)

N.B. That the default for colors is in the API docs is currently wrong, because it's actually based on the presence of colorama and colorama is not present when building the docs.

hynek
  • 3,647
  • 1
  • 18
  • 26