76之logging日志信息log
日志信息排错(举例)
官网链接:https://docs.python.org/zh-tw/3/howto/logging.html
logger.py
import sys
import logging
from logging import handlers
# 日志级别关系映射
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
}
def _get_logger(filename, level='info'):
# 创建日志对象
log = logging.getLogger(filename)
# 设置日志级别
log.setLevel(level_relations.get(level))
# 日志输出格式
fmt = logging.Formatter('%(asctime)s %(thread)d %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
# 输出到控制台
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(fmt)
# 输出到文件
# 日志文件按天进行保存,每天一个日志文件
file_handler = handlers.TimedRotatingFileHandler(filename=filename, when='D', backupCount=1, encoding='utf-8')
# 按照大小自动分割日志文件,一旦达到指定的大小重新生成文件
# file_handler = handlers.RotatingFileHandler(filename=filename, maxBytes=1*1024*1024*1024, backupCount=1, encoding='utf-8')
file_handler.setFormatter(fmt)
log.addHandler(console_handler)
log.addHandler(file_handler)
return log
# 明确指定日志输出的文件路径和日志级别
logger = _get_logger('test.log', 'info')
等级(点包进去源码)
# Default levels and level names, these can be replaced with any positive set
# of values having corresponding names. There is a pseudo-level, NOTSET, which
# is only really there as a lower limit for user-defined levels. Handlers and
# loggers are initialized with NOTSET so that they will log all messages, even
# at user-defined levels.
#
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
调用
这里举例一个demo
log_t.py
from logger import logger
def a():
"""测试专用"""
lis = []
for i in range(30):
lis.append(i)
return lis
if __name__ == '__main__':
res = a()
# logger.info('日志输出测试')
logger.info(res) # 导入包即可
其它py日志文章链接,也可以学习:https://foofish.net/logging.html
本文来自博客园,作者:__username,转载请注明原文链接:https://www.cnblogs.com/code3/p/17120922.html