Python 输出到文件时不显示记录器格式
Python logger formatting not appearing when output to file
我已经将我的 Python 程序设置为记录输出,但是虽然它正确地记录到控制台,但它没有将时间、日志级别信息等记录到文件中。
节目:
import time
import logging
from logging.handlers import RotatingFileHandler
logFileName = 'logs.log'
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
log = logging.getLogger(__name__)
handler = RotatingFileHandler(logFileName , maxBytes=2000 , backupCount=5)
log.addHandler(handler)
log.setLevel(logging.INFO)
if __name__ == '__main__':
while True:
log.info("program running")
time.sleep(1)
输出到控制台:
INFO 05-May-22 23:20:54 - program running
INFO 05-May-22 23:20:55 - program running
INFO 05-May-22 23:20:56 - program running
INFO 05-May-22 23:20:57 - program running
INFO 05-May-22 23:20:58 - program running
INFO 05-May-22 23:20:59 - program running
INFO 05-May-22 23:21:00 - program running
同时输出到文件logs.log:
program running
program running
program running
program running
program running
program running
program running
如何让完整的输出到日志文件?
您可以为RotatingFileHandler
单独设置Formatter
handler.formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
我已经将我的 Python 程序设置为记录输出,但是虽然它正确地记录到控制台,但它没有将时间、日志级别信息等记录到文件中。
节目:
import time
import logging
from logging.handlers import RotatingFileHandler
logFileName = 'logs.log'
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
log = logging.getLogger(__name__)
handler = RotatingFileHandler(logFileName , maxBytes=2000 , backupCount=5)
log.addHandler(handler)
log.setLevel(logging.INFO)
if __name__ == '__main__':
while True:
log.info("program running")
time.sleep(1)
输出到控制台:
INFO 05-May-22 23:20:54 - program running
INFO 05-May-22 23:20:55 - program running
INFO 05-May-22 23:20:56 - program running
INFO 05-May-22 23:20:57 - program running
INFO 05-May-22 23:20:58 - program running
INFO 05-May-22 23:20:59 - program running
INFO 05-May-22 23:21:00 - program running
同时输出到文件logs.log:
program running
program running
program running
program running
program running
program running
program running
如何让完整的输出到日志文件?
您可以为RotatingFileHandler
Formatter
handler.formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')