简体   繁体   中英

python logging only to file

I have a cronjob running a python script which I added a logging to, but since it's a daily job it is really annoying that I get daily emails of it's function, but I can't seem to find a setting, that will make it log only into the logfile.

#!/usr/bin/python
import logging, logging.handlers
LOGFILENAME = "log.log" 
logging.basicConfig()
log = logging.getLogger("nameoflog")
log.setLevel(logging.DEBUG) 
handler = logging.handlers.WatchedFileHandler(LOGFILENAME)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter("%(asctime)-15s %(levelname)-8s %(name)s %(message)s")) 
log.addHandler(handler)
log.info("something happening")

How is it possible to make logging only write to a file and not to file and STDOUT ?

The problem is that you call logging.basicConfig() which sets up logging to stdout . basicConfig is just a helper method used when you don't want to make more detailed logging calls. Since you setup the methods yourself, you should not call basicConfig .

Here's an example that works for me (it does not print the message to stdout, but only to example.log ):

def logToFile():
    import logging
    logging.basicConfig(filename='example.log',level=logging.DEBUG)
    logging.info("trying to log to file")

logToFile()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM