Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TimedRotatingFileHandler logs to a file and stderr

Tags:

python

logging

I am trying to include simple logging into my application using TimedRotatingFileHandler. However I get the output both into the designated file and into the standard error. I reduced the problem to a small example:

import logging, logging.handlers
import sys

logging.basicConfig(format='%(asctime)s %(message)s')
loghandler = logging.handlers.TimedRotatingFileHandler("logfile",when="midnight")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(loghandler)

for k in range(5):
    logger.info("Line %d" %  k)

I get 5 log lines both in my 'logfile' and this program's stderr. What am I doing wrong?

like image 755
Tsf Avatar asked Jul 03 '11 20:07

Tsf


People also ask

What is FileHandler in logging?

FileHandler. The FileHandler class, located in the core logging package, sends logging output to a disk file. It inherits the output functionality from StreamHandler .

What is StreamHandler Python?

Description: - The StreamHandler call located in the core logging package, sends logging output to stream such as sys. stdout, sys. stderr, or any file-like object which supports the write() and flush() method.

Can I have two loggers in Python?

if you transform the second module in a class, you can simply: declare the logger in the first modulue. create the new class passing the 2 logger as parameters. use the logger in the new class.

How do you clear a Python log file?

You'd have to signal to the daemon that the log file's been removed so it can close/reopen the log file handle and start using the new log file. Otherwise it'll just keep writing to the old one, which will still exist somewhere until all filehandles on it are closed. Give mode="w" to logging.


2 Answers

logging.basicConfig sets up a handler that prints to standard error. logger.addHandler(loghandler) sets up a TimedRotatingFileHandler.

Do you wish to squelch output to standard error? If so, simply remove the call tologging.basicConfig.

like image 25
unutbu Avatar answered Sep 19 '22 06:09

unutbu


This is the way you can have the print just on the log files and not to stdout/stderr:

import logging
from logging.handlers import TimedRotatingFileHandler

logHandler = TimedRotatingFileHandler("logfile",when="midnight")
logFormatter = logging.Formatter('%(asctime)s %(message)s')
logHandler.setFormatter( logFormatter )
logger = logging.getLogger( 'MyLogger' )
logger.addHandler( logHandler )
logger.setLevel( logging.INFO )

for k in range(5):
    logger.info("Line %d" %  k)
like image 186
Cinquo Avatar answered Sep 20 '22 06:09

Cinquo