structlog icon indicating copy to clipboard operation
structlog copied to clipboard

Redirecting logs to stderr suppresses colored output

Open meithecatte opened this issue 2 years ago • 1 comments

I would like my application to log to stderr, so that stdout can be used for other purposes. I managed to achieve this with the following configuration:

structlog.configure(logger_factory=structlog.PrintLoggerFactory(sys.stderr))

This means that redirecting the stdout of the python process only gets the data I print, with the logs still going to the terminal — just like I want. However, when I redirect stdout, the logs getting printed to stderr lose their colors. This is because the default processor pipeline hardcodes a check on stdout:

https://github.com/hynek/structlog/blob/181423273425366ae156ece796aa8c39ffd0fb37/src/structlog/_config.py#L46

I am not sure what the best way to fix this is, but it would be nice if choosing stderr instead of stdout didn't require repeating the entire processor pipeline in my code.

meithecatte avatar Jun 15 '23 18:06 meithecatte

That's an a lot bigger ask than it seems. :) You're asking for an easy way to fundamentally change the processors concept of structlog.

For now I have two suggestions:

  • structlog respects FORCE_COLOR=1
  • ConsoleRenderer is always at the end of the processor chain so you can do something like structlog.configure(processors=structlog.get_config()["processors"][:-1] + [structlog.dev.ConsoleRenderer(colors=True)])

hynek avatar Jun 21 '23 12:06 hynek

I have added a note to https://www.structlog.org/en/stable/console-output.html#console-output-configuration how to swap out just the renderer. I don't see any other realistic action on this at this time.

hynek avatar Apr 02 '24 07:04 hynek