Python日志模块的两种用法
生活随笔
收集整理的這篇文章主要介紹了
Python日志模块的两种用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import logging
from logging.handlers import TimedRotatingFileHandler,RotatingFileHandler'''
級別有如下:
level=logging.NOTSET 0
level=logging.DEBUG 10
level=logging.INFO 20
level=logging.WARNING 30
level=logging.ERROR 40
level=logging.CRITICAL 50logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
logging.exception('')捕獲異常#寫法一
logging.basicConfig(filename="test.log", filemode="w",format="%(asctime)s:%(pathname)s:第%(lineno)d行:%(name)s:%(levelname)s:%(message)s",datefmt="%Y-%m-%d %H:%M:%S", level=logging.NOTSET)a = 5
b = 0
try:c = a / blogging.info('This is an info message')
except Exception as e:# 下面三種方式三選一,推薦使用第一種# logging.exception("Exception occurred")# logging.error("Exception occurred", exc_info=True)# logging.log(level=logging.DEBUG, msg="Exception occurred", exc_info=True)logging.error('This is an error message')
'''# 寫法二logger = logging.getLogger("logger")
logger.setLevel(logging.DEBUG)
logger.propagate = Falsehandler1 = logging.StreamHandler()
# handler2 = logging.FileHandler(filename="test.log")
'''
TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])
filename 是輸出日志文件名的前綴when 是一個字符串的定義如下:“S”: Seconds“M”: Minutes“H”: Hours“D”: Days“W”: Week day (0=Monday)“midnight”: Roll over at midnightinterval 是指等待多少個單位when的時間后,Logger會自動重建文件,當然,這個文件的創(chuàng)建取決于filename+suffix,
若這個文件跟之前的文件有重名,則會自動覆蓋掉以前的文件,所以有些情況suffix要定義的不能因為when而重復。backupCount 是保留日志個數。默認的0是不會自動刪除掉日志。若設10,則在文件的創(chuàng)建過程中庫會判斷是否有超過這個10,
若超過,則會從最先創(chuàng)建的開始刪除。
'''
#handler2 = TimedRotatingFileHandler(filename="test.log",when='S', encoding='utf8',interval=3, backupCount=3)
handler2 = RotatingFileHandler(filename="test.log", mode='a',maxBytes=1, encoding='utf8', backupCount=3)'''
handler1.setLevel(logging.WARNING)
handler2.setLevel(logging.WARNING)
'''
format_str = "%(asctime)s:%(pathname)s:第%(lineno)d行:%(name)s:%(levelname)s:%(message)s"
datefmt = '%Y-%m-%d %H:%M:%S'formatter = logging.Formatter(format_str, datefmt)
handler1.setFormatter(formatter)
handler2.setFormatter(formatter)logger.addHandler(handler1)
logger.addHandler(handler2)a = 5
b = 0
try:c = a / blogger.info('This is an info message')
except Exception as e:# 下面三種方式三選一,推薦使用第一種# logging.exception("Exception occurred")# logging.error("Exception occurred", exc_info=True)# logging.log(level=logging.DEBUG, msg="Exception occurred", exc_info=True)logger.error('This is an error message')
來源:https://blog.csdn.net/tangwendi/article/details/94843555
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Python日志模块的两种用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单眼睛斜视怎么矫正(斜视怎么矫正)
- 下一篇: 加里森敢死队(说一说加里森敢死队的简介)