Redirecting logs to stderr suppresses colored output
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.
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)])
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.