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 50


logging.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 / b
    logging.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 = False

handler1 = 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 midnight

interval 是指等待多少个单位when的时间后,Logger会自动重建文件,当然,这个文件的创建取决于filename+suffix,
若这个文件跟之前的文件有重名,则会自动覆盖掉以前的文件,所以有些情况suffix要定义的不能因为when而重复。

backupCount 是保留日志个数。默认的0是不会自动删除掉日志。若设10,则在文件的创建过程中库会判断是否有超过这个10,
若超过,则会从最先创建的开始删除。
'''
#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 / b
    logger.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

发布了44 篇原创文章 · 获赞 130 · 访问量 137万+

猜你喜欢

转载自blog.csdn.net/gb4215287/article/details/105159626
今日推荐