python中的logger之二
生活随笔
收集整理的這篇文章主要介紹了
python中的logger之二
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Rotating-logger
日志文件太大,一般不容易使用。現在的日志系統一般都提供了方便的日志回繞分片。一般有按照文件大小、記錄時間長度來對日志文件分片。
在python logging中,提供了這2種分片方式。
這種方式使用的Handler是RotatingFileHandler;
class RotatingFileHandler(BaseRotatingHandler):"""Handler for logging to a set of files, which switches from one fileto the next when the current file reaches a certain size."""def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):下面看看使用方式:
rlogger = logging.getLogger("loggingtest2") rfh = RotatingFileHandler("log/rtest.log", maxBytes=2000,backupCount=3)formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') rfh.setFormatter(formatter)rlogger.addHandler(rfh)完整示例:
import sys,time import logging from logging.handlers import RotatingFileHandler,TimedRotatingFileHandlerrlogger = logging.getLogger("loggingtest2") rfh = RotatingFileHandler("log/rtest.log", maxBytes=2000,backupCount=3)formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') rfh.setFormatter(formatter)rlogger.addHandler(rfh)rlogger.setLevel(level = logging.INFO)i = 0 while i<2000:rlogger.info("this is a %s %i.......","info",i)rlogger.warning("this is a %s %i........", "warning",i)i=i+1執行時,會在log下生成rtest.log,以及分片的3個backup文件rtest.log.0, rtest.log.1, rtest.log.2
這里使用的是TimedRotatingFileHandler。
定義如下:
class TimedRotatingFileHandler(BaseRotatingHandler):"""Handler for logging to a file, rotating the log file at certain timedintervals.If backupCount is > 0, when rollover is done, no more than backupCountfiles are kept - the oldest ones are deleted."""def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):使用方式:
formatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') trlogger = logging.getLogger() trfh = TimedRotatingFileHandler("log/tr_test.log",when="S",interval=5,backupCount=3)trfh.setFormatter(formatter) trlogger.addHandler(trfh)完整示例:
import sys,time import logging from logging.handlers import RotatingFileHandler,TimedRotatingFileHandlerformatter = logging.Formatter('%(name)-12s %(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') trlogger = logging.getLogger() trfh = TimedRotatingFileHandler("log/tr_test.log",when="S",interval=5,backupCount=3)trfh.setFormatter(formatter) trlogger.addHandler(trfh)trlogger.setLevel(level = logging.INFO)i=0 while i < 500:trlogger.info("this is a %s .......","info")trlogger.warning("this is a %s........", "warning")time.sleep(0.5)i=i+1總結
以上是生活随笔為你收集整理的python中的logger之二的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 曝苹果2025年推出折叠屏MacBook
- 下一篇: 1月份造车新势力成绩单出炉 理想赢麻了