简体   繁体   中英

How to log to file & stdout

I have the following logging set up:

import logging
logging.basicConfig(level=logging.DEBUG,
                format='[%(asctime)s] - %(funcName)s - %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='/tmp/affiliate.log',
                filemode='w')

How would I convert the following two statements -- which writes to the log file and then prints the output:

logging.debug('>>>>> 401 Error: Cannot download file')
print '>>>>> 401 Error: Cannot download file'

Into one logging statement that does both?

You can't do it with just basicConfig (at least not in Python 2.7; 3.3 added new features, in particular the handlers parameter), but it's easy to set up the logger to write to two places. The Logging Cookbook explains how to do all kinds of things in full detail.

A few of the cookbook entries aren't fully explained, just demonstrated, but you can always look up the details in the logging docs.

The key thing you're looking for here is to create two handlers — a FileHandler('/tmp/affiliate.log') , and a StreamHandler(sys.stdout) .

If you want the same format, log level, etc. in both the log file and stdout , one of the early examples in the cookbook does exactly this, except with stderr . If you want different formats for each, the very next example does that .

So, instead of this:

logging.basicConfig(level=logging.DEBUG,
                format='[%(asctime)s] - %(funcName)s - %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='/tmp/affiliate.log',
                filemode='w')

Do this:

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/tmp/affiliate.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] - %(funcName)s - %(message)s',
                               datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)

Note that the second example I linked uses basicConfig to do everything it can do, then adds a second handler on top of it. I think this is a little less clear, but if you want to do the same, you can do it.

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