常用模块logging

常用模块logging

什么时候用到logging模块

1.用来记录用户的行为 - 数据分析
2.用来记录用户的行为 - 操作审计
3.排查代码中的错误

输出内容是有等级的 : 默认处理warning级别以上的所有信息
logging.debug('debug message')          # 调试
logging.info('info message')            # 信息
logging.warning('warning message')      # 警告
logging.error('error message')          # 错误
logging.critical('critical message')    # 批判性的

默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

import logging

file_handler = logging.FileHandler(filename='x1.log', mode='a', encoding='utf-8',)
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    handlers=[file_handler,],
    level=logging.ERROR
)

logging.error('你好')
# 同时向文件和屏幕上输出
fh = logging.FileHandler('tmp.log',encoding='utf-8') #向文件输出
# fh2 = logging.FileHandler('tmp2.log',encoding='utf-8')
sh = logging.StreamHandler()  #向屏幕输出
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s[line :%(lineno)d]-%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    level= logging.DEBUG,
    # handlers=[fh,sh,fh2]
    handlers=[fh,sh]
)
logging.debug('debug 信息错误 test2')
logging.info('warning 信息错误 test2')
logging.warning('warning message test2')
logging.error('error message test2')
logging.critical('critical message test2')

做日志的切分

import time
from logging import handlers
sh = logging.StreamHandler()
rh = handlers.RotatingFileHandler('myapp.log', maxBytes=1024,backupCount=5)   # 按照大小做切割
fh = handlers.TimedRotatingFileHandler(filename='x2.log', when='s', interval=5, encoding='utf-8')
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s[line :%(lineno)d]-%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    level= logging.DEBUG,
    # handlers=[fh,sh,fh2]
    handlers=[fh,rh,sh]
)
for i in range(1,100000):
    time.sleep(1)
    logging.error('KeyboardInterrupt error %s'%str(i))
posted @ 2020-06-14 11:21  爱浪的跳蚤  阅读(104)  评论(0编辑  收藏  举报