1.简单的将日志打印到屏幕

1import logging
2logging.debug('This is debug message')
3logging.info('This is info message')
4logging.warning('This is warning message')
5屏幕上打印:
6WARNING:root:This is warning message

默认情况下,logging将日志打印到屏幕,日志级别为WARNING;日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

 1import logging
 2logging.basicConfig(level=logging.DEBUG,
 3                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
 4                datefmt='%a, %d %b %Y %H:%M:%S',
 5                filename='myapp.log',
 6                filemode='w')
 7logging.debug('This is debug message')
 8logging.info('This is info message')
 9logging.warning('This is warning message')
10./myapp.log文件中内容为:
11Thur, 8 Jan 2015 21:48:54 demo2.py[line:11] DEBUG This is debug message
12Thur, 8 Jan 2015 21:48:54 demo2.py[line:12] INFO This is info message
13Thur, 8 Jan 2015 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函数各参数:

 1filename: 指定日志文件名
 2filemode: 和file函数意义相同,指定日志文件的打开模式,'w''a'
 3format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
 4 %(levelno)s: 打印日志级别的数值
 5 %(levelname)s: 打印日志级别名称
 6 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
 7 %(filename)s: 打印当前执行程序名
 8 %(funcName)s: 打印日志的当前函数
 9 %(lineno)d: 打印日志的当前行号
10 %(asctime)s: 打印日志的时间
11 %(thread)d: 打印线程ID
12 %(threadName)s: 打印线程名称
13 %(process)d: 打印进程ID
14 %(message)s: 打印日志信息
15datefmt: 指定时间格式,同time.strftime()
16level: 设置日志级别,默认为logging.WARNING
17stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

3.将日志同时输出到文件和屏幕

 1import logging
 2logging.basicConfig(level=logging.DEBUG,
 3                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
 4                datefmt='%a, %d %b %Y %H:%M:%S',
 5                filename='myapp.log',
 6                filemode='w')
 7#################################################################################################
 8#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
 9console = logging.StreamHandler()
10console.setLevel(logging.INFO)
11formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
12console.setFormatter(formatter)
13logging.getLogger('').addHandler(console)
14#################################################################################################
15logging.debug('This is debug message')
16logging.info('This is info message')
17logging.warning('This is warning message')
18屏幕上打印:
19root        : INFO     This is info message
20root        : WARNING  This is warning message
21./myapp.log文件中内容为:
22Thur, 8 Jan 2015 21:48:54 demo2.py[line:11] DEBUG This is debug message
23Thur, 8 Jan 2015 21:48:54 demo2.py[line:12] INFO This is info message
24Thur, 8 Jan 2015 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日志回滚

 1import logging
 2from logging.handlers import RotatingFileHandler
 3#################################################################################################
 4#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
 5Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)
 6Rthandler.setLevel(logging.INFO)
 7formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
 8Rthandler.setFormatter(formatter)
 9logging.getLogger('').addHandler(Rthandler)
10################################################################################################

从上例和本例可以看出,logging有一个日志处理的主对象,其它处理方式都是通过addHandler添加进去的。logging的几种handle方式如下:

 1logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件
 2logging.FileHandler: 日志输出到文件
 3日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler
 4logging.handlers.BaseRotatingHandler
 5logging.handlers.RotatingFileHandler
 6logging.handlers.TimedRotatingFileHandler
 7logging.handlers.SocketHandler: 远程输出日志到TCP/IP sockets
 8logging.handlers.DatagramHandler:  远程输出日志到UDP sockets
 9logging.handlers.SMTPHandler:  远程输出日志到邮件地址
10logging.handlers.SysLogHandler: 日志输出到syslog
11logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志
12logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer
13logging.handlers.HTTPHandler: 通过"GET""POST"远程输出到HTTP服务器

由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中,上述其它处理方式的使用请参见python手册!

5.通过logging.config模块配置日志

logger配置文件:

 1#logger.conf
 2###############################################
 3[loggers]
 4keys=root,example01,example02
 5[logger_root]
 6level=DEBUG
 7handlers=hand01,hand02
 8[logger_example01]
 9handlers=hand01,hand02
10qualname=example01
11propagate=0
12[logger_example02]
13handlers=hand01,hand03
14qualname=example02
15propagate=0
16###############################################
17[handlers]
18keys=hand01,hand02,hand03
19[handler_hand01]
20class=StreamHandler
21level=INFO
22formatter=form02
23args=(sys.stderr,)
24[handler_hand02]
25class=FileHandler
26level=DEBUG
27formatter=form01
28args=('myapp.log', 'a')
29[handler_hand03]
30class=handlers.RotatingFileHandler
31level=INFO
32formatter=form02
33args=('myapp.log', 'a', 10*1024*1024, 5)
34###############################################
35[formatters]
36keys=form01,form02
37[formatter_form01]
38format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
39datefmt=%a, %d %b %Y %H:%M:%S
40[formatter_form02]
41format=%(name)-12s: %(levelname)-8s %(message)s
42datefmt=

调用示例:

 1示例1
 2import logging
 3import logging.config
 4logging.config.fileConfig("logger.conf")
 5logger = logging.getLogger("example01")
 6logger.debug('This is debug message')
 7logger.info('This is info message')
 8logger.warning('This is warning message')
 9示例2
10import logging
11import logging.config
12logging.config.fileConfig("logger.conf")
13logger = logging.getLogger("example02")
14logger.debug('This is debug message')
15logger.info('This is info message')
16logger.warning('This is warning message')

6.logging重定向strerr,strout

 1import logging
 2import sys
 3class StreamToLogger(object):
 4   """
 5   Fake file-like stream object that redirects writes to a logger instance.
 6   """
 7   def __init__(self, logger, log_level=logging.INFO):
 8      self.logger = logger
 9      self.log_level = log_level
10      self.linebuf = ''
11   def write(self, buf):
12      for line in buf.rstrip().splitlines():
13         self.logger.log(self.log_level, line.rstrip())
14logging.basicConfig(
15   level=logging.DEBUG,
16   format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',
17   filename="out.log",
18   filemode='a'
19)
20stdout_logger = logging.getLogger('STDOUT')
21sl = StreamToLogger(stdout_logger, logging.INFO)
22sys.stdout = sl
23stderr_logger = logging.getLogger('STDERR')
24sl = StreamToLogger(stderr_logger, logging.ERROR)
25sys.stderr = sl
26print "Test to standard out"
27raise Exception('Test to standard error')

其输出格式类似如下:

 12015-01-08 22:10:20,573:INFO:STDOUT:Test to standard out
 22015-01-08 22:10:20,573:ERROR:STDERR:Traceback (most recent call last):
 32015-01-08 22:10:20,574:ERROR:STDERR:  File "redirect.py", line 33, in
 42015-01-08 22:10:20,574:ERROR:STDERR:raise Exception('Test to standard error')
 52015-01-08 22:10:20,574:ERROR:STDERR:Exception
 62015-01-08 22:10:20,574:ERROR:STDERR::
 72015-01-08 22:10:20,574:ERROR:STDERR:Test to standard error
 82015-01-08 22:10:20,573:INFO:STDOUT:Test to standard out
 92015-01-08 22:10:20,573:ERROR:STDERR:Traceback (most recent call last):
102015-01-08 22:10:20,574:ERROR:STDERR:  File "redirect.py", line 33, in
112015-01-08 22:10:20,574:ERROR:STDERR:raise Exception('Test to standard error')
122015-01-08 22:10:20,574:ERROR:STDERR:Exception
132015-01-08 22:10:20,574:ERROR:STDERR::
142015-01-08 22:10:20,574:ERROR:STDERR:Test to standard error