Warm tip: This article is reproduced from serverfault.com, please click

Python logging format handler stdout default format

发布于 2020-12-01 05:35:17

I'm using logging standard library and add the handler to output to stdout. However, the new handler doesn't seem to have the default logging format, below is the example

In [23]: root = logging.getLogger() 
    ...: handler = logging.StreamHandler(sys.stdout) 
    ...: log_level_int = getattr(logging, "INFO") 
    ...: root.setLevel(log_level_int) 
    ...: handler.setLevel(log_level_int) 
    ...: root.addHandler(handler)          

In [28]: logging.info("test")                                                                                                                                                                                      
INFO:root:test # default stderr handler
test # newly added stdout handler, doesn't have the log level information printed

How can the new stdout handler use the same format as the default?

Questioner
Darren Christopher
Viewed
0
salparadise 2020-12-01 14:35:24

Since you have a custom handler, you need to set the formatter.

In [32]: handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))


In [33]: logging.error('test')
root - ERROR - test

or even the default formatter:

handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))

Available logging attributes

How can the new stdout handler use the same format as the default?

You can also use the logging.basicConfig logging setup.

From the docs:

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.

So something as simple as:

import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.info('test')

results in:

INFO:root:test