Python日志库logging
2014年9月13日
1 概述
python自身使用logging作为日志管理模块,功能强大。
具有传统的文件、格式等设置外,还可以将文件发送到网络等。
2 目标:使用python原生库快速,灵活的记录日志
1) 记录日志文件(根日志配置:logging.basicConfig(key=value))
2) 设置记录级别(key:)
3) 设置记录格式(格式Format)
4) 使用卷动文件记录(日志目标位置Handler)
3 原理:接受日志事件,将日志发送到指定目标。
日志格式与log4cpp的组织相似,以logger代表日志类,树形组织(根名为root),可以派生。
设置日志的各种参数,作为根的默认格式。可以为不同的子日志记录不同的格式。不同的级别,条目也可以单独设置格式。并且各个格式也可以在创建后独立设置/取消。
3.1 logger
是记录的实体,记录日志到文件。如果不设置,则默认是以root为名的logger。一般使用module的名称作为子log名称,便于查找。相当于log4cpp中的Category
3.1.1handler
用于处理日志消息,可以将其发送到网络。是logger的子项。相当于log4cpp中的appender。
3.1.1.1 formatter
用于设置日志条目格式。是handler的属性。相当于log4cpp中的layout。
3.1.2filter
用于将指定名称的日志输出。将指定logger的信息输出到日志,其它不输出。是logger的子项,只能影响当前logger(不能影响子logger)。
日志级别:NOTSET、DEBUG、INFO、WARNING(默认级别)、ERROR、CRITICAL。
所有的配置信息使用键值对表示。
4 方法:
4.1 根日志配置:logging.basicConfig(key=value)
一般只要指定根日志的配置,子日志继承微调即可。
可以通过文件(fileConfig)或程序指定参数。
4.1.1 key:
filename:文件路径。如果不设置,则默认输出到std::out。
filemode:日志打开模式,’a’=append,’w’=truncate。
format:日志条目格式。
level:日志级别。
stream:用于初始化streamHandler的流。
示例:
logging.basicConfig(filename = os.path.join(os.getcwd(),'log.txt'), level = logging.WARN, filemode = 'w', format = '%(asctime)s -%(levelname)s: %(message)s')
4.1.2 格式Format
输出条目格式:在basicConfig中指定format。
输出级别:指定format中的levelname。
输出当前logger的名称:指定format中的name。
输出信息格式:指定format中的message格式。遵循str.format和string.template。
输出时间格式:指定format中的asctime格式。遵循time.strftime。使用datefmt指定格式。
logging.basicConfig(format='%(asctime)s%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
详细输出内容参考:(来源logging.__init__.py)
%(name)s Name of the logger (loggingchannel)
%(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 wherethe 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 loggingcall 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 wascreated
%(msecs)d Millisecond portion of the creationtime
%(relativeCreated)dTime 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
4.2 日志目标位置Handler
需要导入库logging.handlers
指定日志的输出位置。
如果指定filename,则使用fileHandler。输出到文件。
如果指定为RotatingHandler,则使用卷动文件。
class logging.handlers.RotatingFileHandler(filename,mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
5 示例
import os
import logging
import logging.handlers
logging.basicConfig(filename = os.path.join(os.getcwd(),'log.txt'), level = logging.DEBUG,
format="[%(asctime)s-%(levelname)s-%(name)s]%(message)s")
logging.debug('this is a message')
logging.warn("this is a warn")
# default logger
loggerRoot = logging.getLogger("root")
# child logger
loggerC1 = logging.getLogger("root.c1")
loggerC1.setLevel(logging.WARN) #set logger level
loggerC1.debug("this is c1") #do not log
loggerC1.warn("this is c1")
loggerRoot.warn("this is root") #log its child
loggerC1.warn("%s,xx,%s","dsfs","aaaa")#set msg format
hFile = logging.handlers.RotatingFileHandler("rotate.log","a",1024,10)#rollover file log
loggerC1.addHandler(hFile) #add to logger
fC1 =logging.Formatter("[%(asctime)s-%(levelname)s-%(name)s]xxxx%(message)s")
hFile.setFormatter(fC1) #set handler format
loggerD1 = logging.getLogger("root.c1.d1")
filterC1 = logging.Filter(name='root.c1.d1')# root will onlylog this logger
loggerRoot.addFilter(filterC1)#add filter
loggerC1.addFilter(filterC1)
loggerC1.removeFilter(filterC1)#remove one
loggerD1.addFilter(filterC1)
loggerRoot.warn("this is a filter log.")
loggerC1.warn("this is c1,and with handler.")
loggerD1.warn("this is root.c1.d1")
6 参考
Python 2.7.8 Reference
http://blog.youkuaiyun.com/jgood/article/details/4340740
http://blog.youkuaiyun.com/chosen0ne/article/details/7319306