简单的python通过logging打印日志流程

来源:互联网 发布:matlab矩阵最小值位置 编辑:程序博客网 时间:2024/05/02 11:25

python logging包使用整理
使用logging模块打印日志简单流程:
1. 建立日志管理对象:创建日志管理对象使用logging中的getLogger(name=None)方法,当name参数为空时返回根日志管理对象,当name不为空时根据name返回日志管理对象;
2. 设置输出日志级别:通过日志管理对象的setLevel方法设置打印日志级别,在logging包中设置有日志级别CRITICAL = 50,FATAL = CRITICAL, ERROR = 40,WARNING = 30,WARN = WARNING,FO = 20,DEBUG = 10,NOTSET = 0;
3. 新建输出日志管理句柄:这里可以设置日志输出的位置,可以将日志打印到文件或者屏幕,当打印日志到文件时使用logging.handlers.RotatingFileHandler(filename, maxBytes=1000000, backupCount=2)生成输出句柄对象,当打印日志到屏幕时使用logging.StreamHandler(sys.stdout)生成输出句柄对象;
4. 设置日志句柄格式:通过setFormatter(formatter)方法设置输出句柄对象在输出日志时使用的格式。formatter参数为日志格式对象由logging.Formatter(format)创建,format参数为字符串对象对应关系如下
%(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. 将句柄添加入日志对象句柄集:将上面设置好的句柄管理对象通过日志管理对象的addHandler方法,添加到输出句柄管理对象集中。
之后便可以通过日志对象,调用日志打印方法,打印对应级别的日志。例子如下

import loggingimport syslog = logging.getLogger('log')log.setLevel(logging.DEBUG)consoleHandle = logging.StreamHandler(sys.stdout)consoleHandle.setFormatter(logging.Formatter('%(asctime)s %(filename)s %(lineno)d:%(message)s'))log.addHandler(consoleHandle)log.debug('hello world')
0 0
原创粉丝点击