Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging.FileHandler prints messages into standard output

Tags:

python

logging

I am working with Python logging package and I need to log two types of messages:

  1. Messages that should be only logged into standard output
  2. Messages that should be only logged into a file.

However I cannot achieve it. Here is my code:

import logging                                                     

logger = logging.getLogger("file_logger")                          
fh = logging.FileHandler("tmp.log")                                
logger.addHandler(fh)                                              

logging.warning("Message for std output")                          
logging.getLogger("file_logger").warning("Message for file logger")

When I run this script then following messages are printed in terminal:

WARNING:root:Message for std output
WARNING:file_logger:Message for file logger

How can I fix this behavior so "Message for file logger" will be only printed into the file?

like image 480
NShiny Avatar asked Sep 09 '26 15:09

NShiny


1 Answers

You can fix this by turning off propagation like this:

logger.propagate = False

Without this setting the logging call will be propagated up the logging hierarchy to the root logger. The root logger prints to stdout by default, as you have shown in your example.

like image 85
henne90gen Avatar answered Sep 11 '26 04:09

henne90gen