首页 > 编程语言 > 详细

python logging模块

时间:2020-05-20 01:03:30      阅读:66      评论:0      收藏:0      [点我收藏+]

logging日志模块

日志等级

logging.debug(‘Debug log.‘)
logging.info(‘Info log.‘)
logging.warning(‘Warning log.‘)
logging.error(‘Error log.‘)
logging.critical(‘Critical log.‘)

导入模块

import logging

输出日志到屏幕

sh = logging.StreamHandler()  # 实例化屏幕对象
logging.basicConfig(level=logging.INFO,handlers=[sh])  # level指定要输出的日志级别,handlers列表数据类型,指定日志输出到的对象。
logging.info(‘This is a test info log.‘)  # 记录日志并按照指定的方式输出

输出日志到文件

fh = logging.FileHandler(filename=‘test.log‘, encoding=‘utf-8‘)  # 实例化日志文件对象
logging.basicConfig(handlers=[fh])  # 输出日志到指定文件
logging.error(‘This is a test error log.‘)  # 记录日志并按照指定的方式输出

日志切割

根据时间切割

import time
from logging import handlers
th = handlers.TimedRotatingFileHandler(filename=‘test.log‘, when=‘S‘, interval=5, encoding=‘utf-8‘, backupCount=5)  # when时间单位,interval值,backupCount日志留存数
logging.basicConfig(level=logging.INFO,handlers=[th])
logging.indo("This is a test info log.")

根据文件大小切割

from logging import handlers
rh = handlers.RotatingFileHandler(filename=‘test.log‘, maxBytes=100, backupCount=2)  # maxBytes设置文件达到指定大小进行切割,backupCount日志留存数
logging.basicConfig(level=logging.INFO,handlers=[th])
logging.indo("This is a test info log.")

设置日志格式

sh = logging.StreamHandler()
logging.basicConfig(level=logging.INFO,handlers=[sh],format=‘%(asctime)s %(levelname)s %(module)s %(lineno)d lines :%(message)s‘,datefmt="%Y-%m-%d %H:%M:%S")
logging.info("This is a test info log.")
# format: 指定日志的输出格式,
# %(asctime)s 打印日志的时间
# %(levelname)s:打印日志级别的名称
# %(pathname)s:打印当前执行程序的路径
# %(filename)s:打印当前执行程序名
# %(funcName)s:打印日志的当前函数
# %(lineno)d:打印日志的当前行号
# %(thread)d:打印线程ID
# %(threadName)s:打印线程名称
# %(process)d:打印进程ID
# %(message)s:打印日志信息

python logging模块

原文:https://www.cnblogs.com/liy36/p/12920410.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!