3

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
import logging  

LOG_FILENAME = 'example.log'    
logging.propagate = false 

logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)


logging.debug('This message should go to the log file')

try this, it should works you need to disable propagation (The root logger prints to stdout by default) and define the logging level you want in your file.

1 Comment

It's not exactly what I want. You configure root logger to log messages into the file. I want my root logger to print messages into std out. And I want to have separate logger which only prints messages into the file.

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.