Skip to content
Advertisement

duplication of messages in stderr and stdout python logging

I would like to log info and warning level to stdout and error level and above to stderr how can I do it ?

code:

JavaScript

logging.conf

JavaScript

and output after python3 -m tests 1> output.log 2> err.log:

err.log

JavaScript

output.log

JavaScript

Consequently, the output on the console is:

JavaScript

My question is how to make the message not repeat itself ? I want ERROR on strerr and INFO on stdout.

Advertisement

Answer

Because of the way levels work in logging, if you want to restrict stdout to WARNING and below and restrict stderr to ERROR and above, you’ll need to employ filters in the solution. One way of doing it is as follows.

First, add a filters entry parallel to formatters and handlers, to define a couple of filters:

JavaScript

and refer to them in the handler configurations:

JavaScript

and

JavaScript

Filters are just functions, and we’ll define filter_maker as follows:

JavaScript

I’m using a small script and running it directly, and so the filter_maker will be in the __main__ module (as indicated in the “()” lines above). You might need to change that to fit your specific situation.

Now, if I add some lines to log stuff:

JavaScript

and suppose all this is in main.py, then you can run

JavaScript

and then you should see what’s expected:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement