Python——logging模块(日志模块)
按照格式形成相应的日志条目,写入到制定的目录中去。
logging作用:
1. 用户: 打印用户的信息,流程等。
2. 程序员:⑴:统计用
⑵:用来做故障排查的debug
⑶:用来记录错误,完成代码的优化
⑷:计算结果不正确
特点:
- 配置一次,后续调用即可,(放到项目目录中的conf目录)
- 设置level级别时,要和最小写入级别相等。触发告警只能高或持平。
源代码书写方法:
import logging
file_handler = logging.FileHandler('a.txt','a',encoding='utf-8') #日志存放路径
fmtl = logging.Formatter(fmt="%(asctime)s-%(name)s-%(levelname)s") #存放格式
file_handler.setFormatter(fmtl) #进行关联
logger = logging.Logger('日志对象名称,对应的name值',level=logging.ERROR) #设置日志接收等级
logger.addHandler(file_handler) #logger与file_handler对应
logger.error('错误信息')
源码:报错信息等级:
CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0
源码:可以使用的fmt信息:
%(name)s Name of the logger (logging channel) #设置的名称
%(levelno)s Numeric logging level for the message (DEBUG, INFO,WARNING, ERROR, CRITICAL) #报错等级(显示数值)
%(levelname)s Text logging level for the message ("DEBUG", "INFO","WARNING", "ERROR", "CRITICAL") #报错的等级(显示英文)
%(pathname)s Full pathname of the source file where the loggingcall was issued (if available) #完成路径加文件名称
%(filename)s Filename portion of pathname #文件名称
%(module)s Module (name portion of filename) #路径
%(lineno)d Source line number where the logging call was issued(if available) #触发日志行号
%(funcName)s Function name #函数名称
%(created)f Time when the LogRecord was created (time.time()return value) #以time.time形式出现
%(asctime)s Textual time when the LogRecord was created #创建时间
%(msecs)d Millisecond portion of the creation time #毫秒显示
%(relativeCreated)d Time in milliseconds when the LogRecord was created,relative to the time the logging module was loaded(typically at application startup time)
%(thread)d Thread ID (if available) #线程ID
%(threadName)s Thread name (if available) #线程名称
%(process)d Process ID (if available) #内存ID
%(message)s The result of record.getMessage(), computed just asthe record is emitted #接受的信息
常用版本:
import logging
file_handler = logging.FileHandler(filename='a.txt',mode='a',encoding='utf-8')
logging.basicConfig(
format = "————————%(asctime)s-%(levelname)s————————", #指定格式记录,下面指定了全部保存信息,所以这里不用将很多信息都收集。
datefmt= '%Y-%m-%d %H-%M-%S', #指定日期的格式,将毫秒去掉
handlers=[file_handler,],
level= logging.ERROR) #设置接受的报错等级。
try:
int('abc')
except Exception as e:
logging.error(e,exc_info = True) #这里的exc_info指保存全部保存信息,而不只是保存部分。
日志分割:
每隔一段时间生成一个日志文件,而不会是全部都在一个日志文件中。
import logging
from logging import handlers
file_handler = handlers.TimedRotatingFileHandler(filename='a.txt',when='h',interval=1,encoding='utf-8') #将报错文件每1小时创建一个新的文件。格式是:a.txt时间
logging.basicConfig(
format = "————————%(asctime)s-%(levelname)s————————",
datefmt= '%Y-%m-%d %H-%M-%S',
handlers=[file_handler,],
level= logging.ERROR)
时间间隔书写源码:
S - Seconds
M - Minutes
H - Hours
D - Days
midnight - roll over at midnight
W{0-6} - roll over on a certain day; 0 - Monday
输出+多log保存:
import logging
logger = logging.getLogger()
fh = logging.FileHandler('log.log') #创建一个log
fh2 = logging.FileHandler('log2.log') #创建另一个log
sh = logging.StreamHandler() #log输出
logger.addHandler(fh)
logger.addHandler(fh2)
logger.addHandler(sh)
logger.warning('xuan')
最终版:
所有logging模块有关的配置都写到字典中就可以了,更加清晰,方便管理。
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# __author__ = 'XinBing'
import os
import logging
import logging.config
#开始设置输出或报错的日志格式
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d][%(levelname)s][%(message)s]'
simple_format = '[%(levelname)s][%(asctime)s][%filename)s:%(lineno)d]%(message)s'
id_simple_format = '[%levelname)s][%%asctime)s] %(message)s'
#将报错日志文件的路径确定
logfile_dir = os.path.dirname(os.path.abspath(__file__))
logfile_name = 'test.log'
#如果没有路径,将创建一个。
if not os.path.isdir(logfile_dir):
os.mkdir(logfile_dir)
#进行路径和文件的拼接。
logfile_path = os.path.join(logfile_dir, logfile_name)
#自定义日志模块
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
#输出格式设置
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
},
'filters': {},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', #打印到屏幕上
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', #保存到文件
'formatter': 'standard',
'filename': logfile_path, #日志文件,上面设置的路径
'maxBytes': 1024 * 1024 * 5, #日志大小5M
'backupCount': 5,
'encoding': 'utf-8', #日志文件的编码,再也不用担心中文log乱码了
},
},
'loggers': {
#如果想要让logger对象公用一段配置,那么就使用一个key=''的默认配置。
'': {
'handlers': ['default', 'console', ], #写报错时使用哪个handler。
'level': 'DEBUG',
'propagate': True, #向上(更高Level的logger)传递
},
},
}
def load_my_logging_cfg():
logging.config.dictConfig(LOGGING_DIC) #导入上面定义dlogging配置
logger = logging.getLogger(__name__) #生成一个log实例
logger.debug('It works') #记录该文件的运行状态
if __name__ == '__main__':
load_my_logging_cfg()

浙公网安备 33010602011771号