python logging类库使用例子
一、简单使用
def testlogbasic():
import logging
logging.basicconfig(filename = 'log.txt', filemode = 'a', level = logging.notset, format = '%(asctime)s - %(levelname)s: %(message)s')
logging.debug('this is a message')
logging.info("this is a info")
logging.disable(30)#logging.warning
logging.warning("this is a warnning")
logging.critical("this is a critical issue")
logging.error("this is a error")
logging.addlevelname(88,"mycustomerror")
logging.log(88,"this is an my custom error")
try:
raise exception('this is a exception')
except:
logging.exception( 'exception')
logging.shutdown()
testlogbasic()
说明:(此实例为最简单的用法,用来将log记录到log文件中)
1)logging.basicconfig()中定义默认的log到log.txt,log文件为append模式,处理所有的level大于logging.notset的logging,log的格式定义为'%(asctime)s - %(levelname)s: %(message)s';
2)使用logging.debug()...等来log相应level的log;
3)使用logging.disable()来disable某个logging level;
4)使用logging.addlevelname增加自定义的logging level;
5)使用logging.log来log自定义的logging level的log;
输出的text的log如下:
2011-01-18 10:02:45,415 - debug: this is a message
2011-01-18 10:02:45,463 - info: this is a info
2011-01-18 10:02:45,463 - critical: this is a critical issue
2011-01-18 10:02:45,463 - error: this is a error
2011-01-18 10:02:45,463 - mycustomerror: this is an my custom error
2011-01-18 10:02:45,463 - error: exception
traceback (most recent call last):
file "testlog.py", line 15, in testlogbasic
raise exception('this is a exception')
exception: this is a exception
二、logging的level
#logging level
#logging.notset 0
#logging.debug 10
#logging.info 20
#logging.warning 30
#logging.error 40
#logging.critical 50
logging的level对应于一个int,例如10,20...用户可以自定义logging的level。
可以使用logging.setlevel()来指定要处理的logger级别,例如my_logger.setlevel(logging.debug)表示只处理logging的level大于10的logging。
三、handlers
handler定义了log的存储和显示方式。
nullhandler不做任何事情。
streamhandler实例发送错误到流(类似文件的对象)。
filehandler实例发送错误到磁盘文件。
baserotatinghandler是所有轮徇日志的基类,不能直接使用。但是可以使用rotatingfilehandler和timerotatingfilehandler。
rotatingfilehandler实例发送信息到磁盘文件,并且限制最大的日志文件大小,并适时轮徇。
timerotatingfilehandler实例发送错误信息到磁盘,并在适当的事件间隔进行轮徇。
sockethandler实例发送日志到tcp/ip socket。
datagramhandler实例发送错误信息通过udp协议。
smtphandler实例发送错误信息到特定的email地址。
sysloghandler实例发送日志到unix syslog服务,并支持远程syslog服务。
nteventloghandler实例发送日志到windowsnt/2000/xp事件日志。
memoryhandler实例发送日志到内存中的缓冲区,并在达到特定条件时清空。
httphandler实例发送错误信息到http服务器,通过get或post方法。
nullhandler,streamhandler和filehandler类都是在核心logging模块中定义的。其他handler定义在各个子模块中,叫做logging.handlers。
当然还有一个logging.config模块提供了配置功能。
四、filehandler + streamhandler
def testhanderandformat():
import logging
logger = logging.getlogger("simple")
logger.setlevel(logging.debug)
# create file handler which logs even debug messages
fh = logging.filehandler("simple.log")
fh.setlevel(logging.debug)
# create console handler with a higher log level
ch = logging.streamhandler()
ch.setlevel(logging.error)
# create formatter and add it to the handlers
formatter = logging.formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setformatter(formatter)
fh.setformatter(formatter)
# add the handlers to logger
logger.addhandler(ch)
logger.addhandler(fh)
# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
testhanderandformat()
说明:(此实例同时使用filehandler和streamhandler来实现同时将log写到文件和console)
1)使用logging.getlogger()来新建命名logger;
2)使用logging.filehandler()来生成filehandler来将log写入log文件,使用logger.addhandler()将handler与logger绑定;
3)使用logging.streamhandler()来生成streamhandler来将log写到console,使用logger.addhandler()将handler与logger绑定;
4)使用logging.formatter()来构造log格式的实例,使用handler.setformatter()来将formatter与handler绑定;
运行结果
simple.txt
2011-01-18 11:25:57,026 - simple - debug - debug message
2011-01-18 11:25:57,072 - simple - info - info message
2011-01-18 11:25:57,072 - simple - warning - warn message
2011-01-18 11:25:57,072 - simple - error - error message
2011-01-18 11:25:57,072 - simple - critical - critical message
console
2011-01-18 11:25:57,072 - simple - error - error message
2011-01-18 11:25:57,072 - simple - critical - critical message
五、rotatingfilehandler
def testrotating():
import glob
import logging
import logging.handlers
log_filename = 'logging_rotatingfile_example.out'
# set up a specific logger with our desired output level
my_logger = logging.getlogger('mylogger')
my_logger.setlevel(logging.debug)
# add the log message handler to the logger
handler = logging.handlers.rotatingfilehandler(log_filename, maxbytes=20, backupcount=5)
my_logger.addhandler(handler)
# log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
# see what files are created
logfiles = glob.glob('%s*' % log_filename)
for filename in logfiles:
print(filename)
testrotating()
说明:
rotatingfilehandler指定了单个log文件的size的最大值和log文件的数量的最大值,如果文件大于最大值,将分割为多个文件,如果log文件的数量多于最多个数,最老的log文件将被删除。例如此例中最新的log总是在logging_rotatingfile_example.out,logging_rotatingfile_example.out.5中包含了最老的log。
运行结果:
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
六、使用fileconfig来使用logger
import logging
import logging.config
logging.config.fileconfig("logging.conf")
# create logger
logger = logging.getlogger("simpleexample")
# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
logging.conf文件如下:
[loggers]
keys=root,simpleexample
[handlers]
keys=consolehandler
[formatters]
keys=simpleformatter
[logger_root]
level=debug
handlers=consolehandler
[logger_simpleexample]
level=debug
handlers=consolehandler
qualname=simpleexample
propagate=0
[handler_consolehandler]
class=streamhandler
level=debug
formatter=simpleformatter
args=(sys.stdout,)
[formatter_simpleformatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
运行结果:
2005-03-19 15:38:55,977 - simpleexample - debug - debug message
2005-03-19 15:38:55,979 - simpleexample - info - info message
2005-03-19 15:38:56,054 - simpleexample - warning - warn message
2005-03-19 15:38:56,055 - simpleexample - error - error message
2005-03-19 15:38:56,130 - simpleexample - critical - critical message
上一篇: Python中的闭包详细介绍和实例
推荐阅读
-
Python的Flask框架中使用Flask-SQLAlchemy管理数据库的教程
-
Python的Flask框架中使用Flask-Migrate扩展迁移数据库的教程
-
举例讲解Python中metaclass元类的创建与使用
-
C#中通过使用Connection类来实现打开/关闭数据库的代码实例
-
在Python中定义和使用抽象类的方法
-
Python使用Pycrypto库进行RSA加密的方法详解
-
python使用MySQLdb访问mysql数据库的方法
-
Python连接mysql数据库及python使用mysqldb连接数据库教程
-
Windows7下Python3.4使用MySQL数据库
-
Python的网络编程库Gevent的安装及使用技巧