logging模块两种记录日志的方式:
第1种:使用logging提供的模块级别的函数
第2种:使用logging日志系统的四大组件,可凌晨切割时间
例子如下所示:
import logging
import logging.handlers
import datetime
import os
'''
https://blog.csdn.net/lilong117194/article/details/82852054
https://www.cnblogs.com/yyds/p/6901864.html
'''
'''
logging模块两种记录日志的方式:
1.第1种:使用logging提供的模块级别的函数
'''
def log1():
#获取当前路径
curdir = os.path.split(os.path.realpath(__file__))[0]
if not curdir.endswith("/"):
curdir += "/"
#创建日志目录
logdir = curdir + "log/"
if not os.path.exists(logdir):
os.makedirs(logdir)
fileName = logdir + 'test.log'
#日志格式
LOG_FORMAT = "%(asctime)s[%(levelname)s]%(message)s"
#日期格式
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p" # 如01/25/2019 11:08:48 AM
# 设置了日志级别后,只有级别大于或等于该级别的日志才会被记录下来
# 如下日志级别为DEBUG,等级关系为DEBUG<INFO<WARNING<ERROR<CRITICAL
# basicConfig第一次调用时才会起作用,后面再次调用不会产生任何操作(非累加操作)
logging.basicConfig(filename=fileName, level=logging.DEBUG, format=LOG_FORMAT,datefmt=DATE_FORMAT)
#创造一条严重级别为debug的日志记录,两种表示方法
logging.debug(" this ia a debug log 1")
logging.log(logging.DEBUG, "this is a debug log 2")
logging.info(" this is a info log")
logging.warning(" this is a warning log")
logging.error(" this is a error log")
logging.critical(" this is a critical log")
'''
第二种:使用logging日志系统的四大组件,可凌晨切割时间
loggers(日志器):提供应用程序代码直接使用的接口
handlers(处理器):用于将日志记录发送到指定的目的位置(文件,网络等)
filters(过滤器):提供更细粒度的日志过滤功能,用于决定哪些日志记录将会被输出(其它的日志记录将会被忽略)
formatters(格式器):用于控制日志信息的最终输出格式
'''
def log2():
logger = logging.getLogger('myLogger')
logger.setLevel(logging.DEBUG)
#利用TimedRotatingFileHandler处理器实现按天数分割日志文件
#when=midnight和interval表示每隔一天的午夜,backupCount决定留几个日志文件,0表示全留,datetime.time(0,0,0,0)表示00:00:00
handler1 = logging.handlers.TimedRotatingFileHandler('debug.log',when='midnight',interval=1,backupCount=7,atTime=datetime.time(0,0,0,0))
handler1.setFormatter(logging.Formatter("[%(asctime)s][%(levelname)s]:%(message)s","%Y-%m-%d %H:%M:%S")) #asctime设日期格式如2019-01-25 19:00:15形式
# 设置切割后日志的后缀名称
handler1.suffix = "%Y%m%d"
handler2 = logging.FileHandler('error.log')
handler2.setLevel(logging.ERROR)
#lineno表示代码行号,
handler2.setFormatter(logging.Formatter("%(asctime)s-%(levelname)s-%(filename)s[:%(lineno)d]-%(message)s")) #asctime这些参数详见:https://www.jb51.net/article/88449.htm
#日志器设置两个处理器
logger.addHandler(handler1)
logger.addHandler(handler2)
#记录日志信息
logger.debug('debug message')
logger.info('info message')
logger.warning('waring message')
logger.error('error message')
logger.critical('critical message')
if __name__ == "__main__":
log1()
log2()