python 日志模块logging

logging模块的四大组件
组件名称对应类名功能描述
日志器 Logger 提供了应用程序可一直使用的接口
处理器 Handler 将logger创建的日志记录发送到合适的目的输出
过滤器 Filter 提供了更细粒度的控制工具来决定输出哪条日志记录,丢弃哪条日志记录
格式器 Formatter 决定日志记录的最终输出格式

 

import logging
from logging import handlers
logger = logging.getLogger() #先实例化一个logger对象,先创建一个办公室

logger.setLevel(logging.DEBUG) #设置日志的级别的人
cl = logging.StreamHandler() #负责往控制台输出的人
bl = handlers.TimedRotatingFileHandler(filename='a.log',when='S',interval=1,backupCount=5,encoding='utf-8')
# when,按什么单位
#S 秒
# M 分
# H 小时、
# D 天、
# W 每星期(interval==0时代表星期一)

# midnight - roll over at midnight

# W{0-6} - roll over on a certain day; 0 - Monday


fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
cl.setFormatter(fmt) #设置控制台输出的日志格式
bl.setFormatter(fmt) #设置文件里面写入的日志格式
logger.addHandler(cl) #把已经调教好的人放到办公室里
logger.addHandler(bl) ##把已经调教好的人放到办公室里
#指定日志的格式
logger.debug('我是debug。。。')
logger.warning('我是waring。。。')

 


 

日志格式

 1     %(name)s            Name of the logger (logging channel)
 2     %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
 3                         WARNING, ERROR, CRITICAL)
 4     %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
 5                         "WARNING", "ERROR", "CRITICAL")
 6     %(pathname)s        Full pathname of the source file where the logging
 7                         call was issued (if available)
 8     %(filename)s        Filename portion of pathname
 9     %(module)s          Module (name portion of filename)
10     %(lineno)d          Source line number where the logging call was issued
11                         (if available)
12     %(funcName)s        Function name
13     %(created)f         Time when the LogRecord was created (time.time()
14                         return value)
15     %(asctime)s         Textual time when the LogRecord was created
16     %(msecs)d           Millisecond portion of the creation time
17     %(relativeCreated)d Time in milliseconds when the LogRecord was created,
18                         relative to the time the logging module was loaded
19                         (typically at application startup time)
20     %(thread)d          Thread ID (if available)
21     %(threadName)s      Thread name (if available)
22     %(process)d         Process ID (if available)
23     %(message)s         The result of record.getMessage(), computed just as
24                         the record is emitted

 

posted @ 2019-03-22 17:37  静心_心静  阅读(155)  评论(0编辑  收藏  举报