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?
FileHandler. The FileHandler class, located in the core logging package, sends logging output to a disk file. It inherits the output functionality from StreamHandler .
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.
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.
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.
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With