python 中的logging模块,日志的输出
logging是python提供的log日志模块的一个标准库;
logging模块里提供了不同的方法及类,方便我们对日志输出的一个管理;
日志的四大组件:
1、日志 收集器 logging 使用getLogger()方法
2、handler 日志 处理器 设置日志输出渠道(控制台 还是文件)
3、Formatter 格式器 (设置日志输出格式)
4、fittler 过滤器:保留感兴趣的东西
-----
1、如FileHandler是logging模块里的一个类;该类提供了创建一个日志输出渠道;该类的init方法如下(官方给出的):
def __init__(self, filename, mode='a', encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. """
2、getLogger方法,是创建一个日志收集器,官方给定义如下
def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger.
3、而设置日志等级,用到的方法是setLevel(),官方给出如下用法:
def setLevel(self, level): """ Set the logging level of this handler. level must be an int or a str. """
4、设置日志输出格式,logging模块提供了一个类,Formatter,该类可以对日志的输出格式进行设置
class Formatter(object): """ Formatter instances are used to convert a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the default value of "%s(message)" is used. The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by: %(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 logging call 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) %(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) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted """
5 为日志输出渠道设置日志格式的方法
def setFormatter(self, fmt): """ Set the formatter for this handler. """
具体代码如下:
import logging def handle_log(name,level,filename,fh_level): # 1\创建日志收集器 log=logging.getLogger(name) # 2/设置日志收集器的等级 log.setLevel(level) # 3/设置日志输出渠道 fh=logging.FileHandler(filename,'w',encoding='utf-8') # 设置输出渠道的日志等级 fh.setLevel(fh_level) # 绑定输出渠道到日志收集器 log.addHandler(fh) # 设置日志输出渠道到控制台 sh=logging.StreamHandler() sh.setLevel('INFO') log.addHandler(sh) # 4/设置日志输出格式 formats='' # 创建格式对象 log_format=logging.Formatter('%(asctime)s----%(levelname)s--%(lineno)d-:%(message)s') # 为输出渠道设置日志格式 fh.setFormatter(log_format) sh.setFormatter(log_format) return log if __name__=='__main__': my_log=handle_log('mylog','DEBUG','mylog.log','DEBUG') my_log.info('------info------') my_log.debug('--------debug--------') my_log.error('--------error-------')
6、生成滚动日志,就是当一个日志的大小达到指定大小时,会创建新的日志;用到handlers.RotatingFileHandler;
class RotatingFileHandler(BaseRotatingHandler): """ Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size. """ def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs.
使用和Filehandler创建的类似:
mport logging from logging import handlers def handle_log(): log=logging.getLogger('mylog') log.setLevel('INFO') fh=handlers.RotatingFileHandler('filename.log', maxBytes=4, backupCount=3) fh.setLevel('INFO') log.addHandler(fh) format=logging.Formatter('%(asctime)s ---%(funcName)s---%(levelname)s --%(thread)d---%(process)d --%(message)s') fh.setFormatter(format) return log if __name__=='__main__': log=handle_log() log.info('----info---') log.debug('---debug---') log.error('-----error---')
像上面这段代码,创建的日志文件,如果日志文件达到设定的大小后,会自动备份到filename.log.1;最新的一直是filename.log
二、日志的级别:下面按日志级别从低到高:
debug:调试级别(一般是开发时)
info:关键事件记录
warning:警告信息
error:错误信息
critical:严重错误
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?