简体   繁体   中英

Using python logging with WatchedFileHandler

I'm trying to set up a logger which logs stuff from my script. Occasionally I will move this logfile over to another named file for archiving, and I want the logfile to be recreated if it's missing. As I understand, this is what WatchedFileHandler does. However, in the past I've only set up loggers using the basicConfig setup, and never added handlers explicitly. I tried to do this with the following code snippet

logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',level=logging.DEBUG,filename='logfile',filemode='w',datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger()
log_handler = logging.handlers.WatchedFileHandler('logfile')
logger.addHandler(log_handler)

but this didn't really work. The logfile was indeed recreated after I had moved it over to another name on disk, but my logging format was not present in the logfile. I tried running basicConfig after I called getLogger() too but that didn't help either.

What am I doing incorrectly here?

您需要将Formatter实例添加到具有所需格式的处理程序中( basicConfig()会为您添加到根记录器的处理程序执行此操作)。

log_handler.setFormatter(logging.Formatter('%(levelname)s:%(asctime)s:%(message)s'))

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