pythonlogging模块学习笔记

模块级函数

logging.getlogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug()、logging.info()、logging.warning()、logging.error()、logging.critical():设定root logger的日志级别logging.basicconfig():用默认formatter为日志系统建立一个streamhandler,设置基础配置并加到root logger中

示例:logging_level_example.py

代码如下:

import loggingimport syslevels = {‘debug’: logging.debug, ‘info’: logging.info, ‘warning’: logging.warning, ‘error’: logging.error, ‘critical’: logging.critical}if len(sys.argv) > 1: level_name = sys.argv[1] level = levels.get(level_name, logging.notset) logging.basicconfig(level=level)logging.debug(‘this is a debug message’)logging.info(‘this is an info message’)logging.warning(‘this is a warning message’)logging.error(‘this is an error message’)logging.critical(‘this is a critical error message’)

输出:

代码如下:

$ python logging_level_example.py debugdebug:root:this is a debug messageinfo:root:this is an info messagewarning:root:this is a warning messageerror:root:this is an error messagecritical:root:this is a critical error message

$ python logging_level_example.py infoinfo:root:this is an info messagewarning:root:this is a warning messageerror:root:this is an error messagecritical:root:this is a critical error message

loggers

logger.setlevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高logger.addfilter(filt)、logger.removefilter(filt):添加或删除指定的filterlogger.addhandler(hdlr)、logger.removehandler(hdlr):增加或删除指定的handlerlogger.debug()、logger.info()、logger.warning()、logger.error()、logger.critical():可以设置的日志级别

示例:simple_logging_module.py

代码如下:

import logging# create loggerlogger = logging.getlogger(“simple_example”)logger.setlevel(logging.debug)# create console handler and set level to debugch = logging.streamhandler()ch.setlevel(logging.debug)# create formatterformatter = logging.formatter(“%(asctime)s – %(name)s – %(levelname)s – %(message)s”)# add formatter to chch.setformatter(formatter)# add ch to loggerlogger.addhandler(ch)# “application” codelogger.debug(“debug message”)logger.info(“info message”)logger.warn(“warn message”)logger.error(“error message”)logger.critical(“critical message”)

输出:

代码如下:

$ python simple_logging_module.py2005-03-19 15:10:26,618 – simple_example – debug – debug message2005-03-19 15:10:26,620 – simple_example – info – info message2005-03-19 15:10:26,695 – simple_example – warning – warn message2005-03-19 15:10:26,697 – simple_example – error – error message2005-03-19 15:10:26,773 – simple_example – critical – critical message

handlers

handler对象负责发送相关的信息到指定目的地。可以通过addhandler()方法添加多个多handlerhandler.setlevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略handler.setformatter():给这个handler选择一个格式handler.addfilter(filt)、handler.removefilter(filt):新增或删除一个filter对象

formatters

formatter对象设置日志信息最后的规则、结构和内容,默认的时间格式为%y-%m-%d %h:%m:%s,下面是formatter常用的一些信息

%(name)s

logger的名字

%(levelno)s

数字形式的日志级别

%(levelname)s

文本形式的日志级别

%(pathname)s

调用日志输出函数的模块的完整路径名,可能没有

%(filename)s

调用日志输出函数的模块的文件名

%(module)s

调用日志输出函数的模块名

%(funcname)s

调用日志输出函数的函数名

%(lineno)d

调用日志输出函数的语句所在的代码行

%(created)f

当前时间,用unix标准的表示时间的浮 点数表示

%(relativecreated)d

输出日志信息时的,自logger创建以 来的毫秒数

%(asctime)s

字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d

线程id。可能没有

%(threadname)s

线程名。可能没有

%(process)d

进程id。可能没有

%(message)s

用户输出的消息

最后来个完整例子:

代码如下:

import logging# set up logging to file – see previous section for more detailslogging.basicconfig(level=logging.debug, format=’%(asctime)s %(name)-12s %(levelname)-8s %(message)s’, datefmt=’%m-%d %h:%m’, filename=’/temp/myapp.log’, filemode=’w’)# define a handler which writes info messages or higher to the sys.stderrconsole = logging.streamhandler()console.setlevel(logging.info)# set a format which is simpler for console useformatter = logging.formatter(‘%(name)-12s: %(levelname)-8s %(message)s’)# tell the handler to use this formatconsole.setformatter(formatter)# add the handler to the root loggerlogging.getlogger(”).addhandler(console)# now, we can log to the root logger, or any other logger. first the root…logging.info(‘jackdaws love my big sphinx of quartz.’)# now, define a couple of other loggers which might represent areas in your# application:logger1 = logging.getlogger(‘myapp.area1’)logger2 = logging.getlogger(‘myapp.area2’)logger1.debug(‘quick zephyrs blow, vexing daft jim.’)logger1.info(‘how quickly daft jumping zebras vex.’)logger2.warning(‘jail zesty vixen who grabbed pay from quack.’)logger2.error(‘the five boxing wizards jump quickly.’)

运行后,在终端看到的结果

代码如下:

root : info jackdaws love my big sphinx of quartz.myapp.area1 : info how quickly daft jumping zebras vex.myapp.area2 : warning jail zesty vixen who grabbed pay from quack.myapp.area2 : error the five boxing wizards jump quickly.

在日志文件中的结果

代码如下:

10-22 22:19 root info jackdaws love my big sphinx of quartz.10-22 22:19 myapp.area1 debug quick zephyrs blow, vexing daft jim.10-22 22:19 myapp.area1 info how quickly daft jumping zebras vex.10-22 22:19 myapp.area2 warning jail zesty vixen who grabbed pay from quack.10-22 22:19 myapp.area2 error the five boxing wizards jump quickly.

发现debug信息只有在文件中出现,这是因为streamhandler中setlevel是info,可以看出logger.setlevel()和handler.setlevel()的区别

详细信息请参阅 http://docs.python.org/library/logging.html

Posted in 未分类

发表评论