1

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.