Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1375163
  • 博文数量: 247
  • 博客积分: 10147
  • 博客等级: 上将
  • 技术积分: 2776
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-24 15:18
文章分类

全部博文(247)

文章存档

2013年(11)

2012年(3)

2011年(20)

2010年(35)

2009年(91)

2008年(87)

我的朋友

分类: Python/Ruby

2013-03-20 18:10:34

http://blog.csdn.net/ablo_zhou/article/details/5399449


一、我写的log4py介绍

 

在写< >时,自己实现了简单的log系统:

  1. #!/bin/env python   
  2. #--*-- coding=utf8 --*--   
  3. #   
  4. #   Author: ablozhou   
  5. #   E-mail: ablozhou@gmail.com   
  6. #   
  7. #   Copyright 2010 ablozhou   
  8. #   
  9. #   Distributed under the terms of the GPL (GNU Public License)   
  10. #   
  11. #   hzdq is free software; you can redistribute it and/or modify   
  12. #   it under the terms of the GNU General Public License as published by   
  13. #   the Free Software Foundation; either version 2 of the License, or   
  14. #   (at your option) any later version.   
  15. #   
  16. #   This program is distributed in the hope that it will be useful,   
  17. #   but WITHOUT ANY WARRANTY; without even the implied warranty of   
  18. #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the   
  19. #   GNU General Public License for more details.   
  20. #   
  21. #   You should have received a copy of the GNU General Public License   
  22. #   along with this program; if not, write to the Free Software   
  23. #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA   
  24. #   
  25. # 2010.3.14 写文件,log级别常数定义   
  26. import datetime  
  27. import sys  
  28. import traceback  
  29. import codecs  
  30. import types  
  31. #log编码全部按utf8处理   
  32. loglevels = {'stdout':['info','debug','warn','error','fatal'],  
  33.     'file':['info','debug','warn','error','fatal']  
  34.     }  
  35. logfile = 'logs.txt'  
  36. class log4py:  
  37.     def __init__(self,modulename='gloabal', loglevel=loglevels, filename='log4py.txt'):  
  38.         self.filename = filename  
  39.         #self.flag = set(loglevel['stdout']+loglevel['file'])   
  40.         self.loglevel = loglevel  
  41.         self.modulename = modulename  
  42.         self.fcname = None  
  43.     class function():  
  44.         def __init__(self,fcname,parent):  
  45.             parent.debug('enter ',fcname)  
  46.             self.fcname = fcname  
  47.             self.parent = parent  
  48.         def __del__(self):  
  49.             self.parent.debug('exit ',self.fcname)  
  50.     def dbgfc(self,fcname):  
  51.         '''''set debug function name'''  
  52.         f = None  
  53.         if 'debug' in self.flag:  
  54.             f = self.function(fcname,self)  
  55.         return f  
  56.     def _gettime(self):  
  57.         return datetime.datetime.now().isoformat()  
  58.     def outstd(self,*fmt):  
  59.         s = self.fmtstr(*fmt)  
  60.         print s  
  61.     def outfile(self,*fmt):  
  62.         s = self.fmtstr(*fmt)  
  63.         #print 'before outfile '+s   
  64.         if s:  
  65.             #print 'outfile '+s   
  66.             encoding = 'utf8'  
  67.             out = open(logfile, 'a+')#, encoding   
  68.             out.write(s)  
  69.             out.write('/n')  
  70.             out.close()  
  71.     def fmtstr(self, *fmt):  
  72.         str = ''  
  73.         encoding = 'utf8'#缺省utf8编码   
  74.         for i in fmt:  
  75.             if not type(i) in [types.UnicodeType, types.StringTypes, types.StringType]:  
  76.                 s= repr(i)  
  77.             else:  
  78.                 s = i  
  79.             if type(s) == type(u''):  
  80.                 str += s.encode(encoding)  
  81.             else:  
  82.                 str += s  
  83.             str += '.'  
  84.         #str += '/n'   
  85.         #print 'fmtstr:'+str   
  86.         return str  
  87.     def debug(self,*fmt):  
  88.         if 'debug' in self.loglevel['stdout']:  
  89.             self.outstd(self._gettime(),'[DEBUG]',self.modulename,*fmt)  
  90.         if 'debug' in self.loglevel['file']:  
  91.             #print 'debug file ...'   
  92.             self.outfile(self._gettime(),'[DEBUG]',self.modulename,*fmt)  
  93.     def warn(self,*fmt):  
  94.         if 'warn' in self.loglevel['stdout']:  
  95.             self.outstd(self._gettime(),'[WARN]',self.modulename,*fmt)  
  96.         if 'warn' in self.loglevel['file']:  
  97.             self.outfile(self._gettime(),'[WARN]',self.modulename,*fmt)  
  98.     def info(self,*fmt):  
  99.         if 'info' in self.loglevel['stdout']:  
  100.             self.outstd(self._gettime(),'[INFO]',self.modulename,*fmt)  
  101.         if 'info' in self.loglevel['file']:  
  102.             self.outfile(self._gettime(),'[INFO]',self.modulename,*fmt)  
  103.     def error(self,*fmt):  
  104.         #print '/033[0;30;41m',   
  105.         if 'error' in self.loglevel['stdout']:  
  106.             self.outstd(self._gettime(),'[ERROR]',self.modulename,*fmt)  
  107.         if 'error' in self.loglevel['file']:  
  108.             self.outfile(self._gettime(),'[ERROR]',self.modulename,*fmt)  
  109.         #print '/033[0m'   
  110.     def fatal(self,*fmt):  
  111.         if 'fatal' in self.loglevel['stdout']:  
  112.             self.outstd(self._gettime(),'[FATAL',self.modulename,*fmt)  
  113.         if 'fatal' in self.loglevel['file']:  
  114.             self.outfile(self._gettime(),'[FATAL',self.modulename,*fmt)  
  115. #unit test   
  116. if __name__ == '__main__':  
  117.     log=log4py()  
  118.     log.outstd('INFO','stdout','test')  
  119.     log.outfile('INFO','stdout','test')  
  120.     log.debug('debug information 调试')  
  121.     log.error('errorrrrrrrrrrrrrrr')  
  122.     log.debug('hello')  
#!/bin/env python #--*-- coding=utf8 --*-- # # Author: ablozhou # E-mail: ablozhou@gmail.com # # Copyright 2010 ablozhou # # Distributed under the terms of the GPL (GNU Public License) # # hzdq is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # 2010.3.14 写文件,log级别常数定义 import datetime import sys import traceback import codecs import types #log编码全部按utf8处理 loglevels = {'stdout':['info','debug','warn','error','fatal'], 'file':['info','debug','warn','error','fatal'] } logfile = 'logs.txt' class log4py: def __init__(self,modulename='gloabal', loglevel=loglevels, filename='log4py.txt'): self.filename = filename #self.flag = set(loglevel['stdout']+loglevel['file']) self.loglevel = loglevel self.modulename = modulename self.fcname = None class function(): def __init__(self,fcname,parent): parent.debug('enter ',fcname) self.fcname = fcname self.parent = parent def __del__(self): self.parent.debug('exit ',self.fcname) def dbgfc(self,fcname): '''set debug function name''' f = None if 'debug' in self.flag: f = self.function(fcname,self) return f def _gettime(self): return datetime.datetime.now().isoformat() def outstd(self,*fmt): s = self.fmtstr(*fmt) print s def outfile(self,*fmt): s = self.fmtstr(*fmt) #print 'before outfile '+s if s: #print 'outfile '+s encoding = 'utf8' out = open(logfile, 'a+')#, encoding out.write(s) out.write('/n') out.close() def fmtstr(self, *fmt): str = '' encoding = 'utf8'#缺省utf8编码 for i in fmt: if not type(i) in [types.UnicodeType, types.StringTypes, types.StringType]: s= repr(i) else: s = i if type(s) == type(u''): str += s.encode(encoding) else: str += s str += '.' #str += '/n' #print 'fmtstr:'+str return str def debug(self,*fmt): if 'debug' in self.loglevel['stdout']: self.outstd(self._gettime(),'[DEBUG]',self.modulename,*fmt) if 'debug' in self.loglevel['file']: #print 'debug file ...' self.outfile(self._gettime(),'[DEBUG]',self.modulename,*fmt) def warn(self,*fmt): if 'warn' in self.loglevel['stdout']: self.outstd(self._gettime(),'[WARN]',self.modulename,*fmt) if 'warn' in self.loglevel['file']: self.outfile(self._gettime(),'[WARN]',self.modulename,*fmt) def info(self,*fmt): if 'info' in self.loglevel['stdout']: self.outstd(self._gettime(),'[INFO]',self.modulename,*fmt) if 'info' in self.loglevel['file']: self.outfile(self._gettime(),'[INFO]',self.modulename,*fmt) def error(self,*fmt): #print '/033[0;30;41m', if 'error' in self.loglevel['stdout']: self.outstd(self._gettime(),'[ERROR]',self.modulename,*fmt) if 'error' in self.loglevel['file']: self.outfile(self._gettime(),'[ERROR]',self.modulename,*fmt) #print '/033[0m' def fatal(self,*fmt): if 'fatal' in self.loglevel['stdout']: self.outstd(self._gettime(),'[FATAL',self.modulename,*fmt) if 'fatal' in self.loglevel['file']: self.outfile(self._gettime(),'[FATAL',self.modulename,*fmt) #unit test if __name__ == '__main__': log=log4py() log.outstd('INFO','stdout','test') log.outfile('INFO','stdout','test') log.debug('debug information 调试') log.error('errorrrrrrrrrrrrrrr') log.debug('hello')


 

输出

INFO.stdout.test.
2010-03-20T09:19:47.091774.[DEBUG].gloabal.debug information 调试.
2010-03-20T09:19:47.092294.[ERROR].gloabal.errorrrrrrrrrrrrrrr.
2010-03-20T09:19:47.092568.[DEBUG].gloabal.hello.

 

使用时,只需

import log4py

log = log4py.log4py('module name')

 

就可以用log.debug('debug')等几个级别打印log了。还可以定义是标准输出还是输出到文件,输出什么级别的。适用于小型的log系统。

 

该log4py的好处是使用起来简单,具有基本的级别定义,完全支持中文,log调试的输入除了字符串还支持列表,字典,数字等,可以打印exception信息。打印的格式为"时间到毫秒,模块名,log级别,log内容“。

 

但与系统的log比起来,缺乏强大的定制能力。

 

二、系统的logging模块

著名的log4j,log4cpp,以及python自带的logging其配置都相当复杂,使用灵活,可以通过配置文件自定义输出哪些模块,输出级别,输出格式,输出到文件和标准输出。并且兼顾多线程,性能等。

 

系统自带的logging模块,缺省就可以简单使用:

>>> import logging
>>> logging.debug('debug')
>>> logging.warn('debug')
WARNING:root:debug
>>> logging.debug('你好,调试')
>>> logging.warn('你好,调试')
WARNING:root:你好,调试

 

可见,在控制台,debug缺省是不打印的。

可以在编程时直接控制log的方式,也可以通过配置文件来进行。当然,配置文件更灵活。

 

2.1 logging的几个组件

Logger,Manager, Handler,Filter,Formatter,Configuration,Level

Logger 是应用中log的实例,Handler是输出的方式,如:

  • StreamHandler - logging to a stream, defaulting to sys.stderr.
  • FileHandler - logging to disk files.
  • RotatingFileHandler - logging to disk files with support for rollover, rotating files.
  • SocketHandler - logging to a streaming socket.
  • DatagramHandler - logging to a UDP socket.
  • SMTPHandler - logging to an email address.
  • SysLogHandler - logging to Unix syslog. Contributed by Nicolas Untz, based on .
  • MemoryHandler - buffering records in memory until a specific trigger occurs (or until the buffer gets full).
  • NTEventLogHandler - writes events to the NT event log. For this to work, you need to have Mark Hammond's Win32 extensions installed. (Though of course you can still log to NT from other platforms - just use SocketHandler to redirect to an NT machine).
  • HTTPHandler - sends events to a Web server using either GET or POST semantics.

Filter是设置的模块,哪些需要记录,都可以配置。

Formatter是输出的格式,可以格式化时间,模块,级别。

Level是输出的级别,有如下级别:

DEBUG
INFO
WARNING
ERROR
CRITICAL

log4j等原来的版本最高级是FATAL,python的logging最高级别是CTITICAL,因为FATAL是系统崩溃的错误。

 

下面是一个使用配置文件写log的例子:

  1. #!/usr/bin/env python   
  2. #coding:utf8   
  3. #author 周海汉   
  4. #date:2010.3.20   
  5. #file testlog.py   
  6. import logging  
  7. import logging.config  
  8. logconf = '/home/zhouhh/logconf.ini'  
  9. logging.config.fileConfig(fname=logconf)  
  10. log1 = logging.getLogger('modlog1')  
  11. log1.debug('log1调试信息')  
  12. log1.warn('log1警告信息')  
  13. log1.error('log1 error错误信息')  
  14. log2 =  logging.getLogger('modlog1.modlog2')  
  15. log2.debug('log2调试信息')  
  16. log2.warn('log2警告信息')  
  17. log2.error('log2 错误信息')  
#!/usr/bin/env python #coding:utf8 #author 周海汉 #date:2010.3.20 #file testlog.py import logging import logging.config logconf = '/home/zhouhh/logconf.ini' logging.config.fileConfig(fname=logconf) log1 = logging.getLogger('modlog1') log1.debug('log1调试信息') log1.warn('log1警告信息') log1.error('log1 error错误信息') log2 = logging.getLogger('modlog1.modlog2') log2.debug('log2调试信息') log2.warn('log2警告信息') log2.error('log2 错误信息')


 

配置文件放在/home/zhouhh/logconf.ini

  1. # --- logconf.ini ------------  
  2. [loggers]  
  3. keys=root,modlog1,modlog2  
  4.   
  5. [handlers]  
  6. keys=hd1,hd2  
  7.   
  8. [formatters]  
  9. keys=fmt1,fmt2  
  10. #root logger   
  11. #  
  12. #level: DEBUG, INFO, WARN, ERROR, CRITICAL  , NOTSET.  
  13. # 在root logger, NOTSET 表示记录所有信息.  
  14. #propagate 表示该logger是否从父logger中传送handler  
  15. # channel 表示logger内通道名最低的部分,如 logger 名 "a.b.c", 该值是 "c".  
  16. #  
  17. #parent 表示父 logger名,但root的父log是 "(root)" 而不是 "root".  
  18. #  
  19. #qualname 完全的通道名 ,如logger 名是 "a.b.c", 该值即 "a.b.c".  
  20. #  
  21. #handlers 是本logger附带的逗号隔开的操作者名  
  22. #qualname=(root)用于root  
  23. #propagate=1 用于非root的loggers  
  24. [logger_root]  
  25. level=NOTSET  
  26. handlers=hd1  
  27. qualname=(root)   
  28. propagate=1   
  29. channel=  
  30. parent=  
  31. #如果是NOTSET,表示查看父logger  
  32. #propagate=0表示当root,1表示继承父logger  
  33. [logger_modlog1]  
  34. level=DEBUG   
  35. propagate=1   
  36. qualname=modlog1  
  37. handlers=hd2  
  38. channel=modlog1  
  39. parent=(root)  
  40.   
  41. [logger_modlog2]  
  42. level=WARN  
  43. propagate=1  
  44. qualname=modlog1.modlog2  
  45. handlers=hd2  
  46. channel=modlog2  
  47. parent=modlog1  
  48. #NOTSET从父logger继承  
  49. #formatter留空表示logging._defaultFormatter  
  50. [handler_hd1]  
  51. class=StreamHandler   
  52. level=DEBUG  
  53. formatter=fmt1    
  54. args=(sys.stdout,)  
  55. stream=sys.stdout  
  56.   
  57. [handler_hd2]  
  58. class=FileHandler  
  59. level=DEBUG  
  60. formatter=fmt2  
  61. args=('python.log''w')  
  62. filename=python.log  
  63. mode=w  
  64. [formatter_fmt1]  
  65. format=F1 %(asctime)s %(levelname)s %(message)s  
  66. datefmt=  
  67. [formatter_fmt2]  
  68. format=F2 %(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s  
  69. datefmt=  
# --- logconf.ini ------------ [loggers] keys=root,modlog1,modlog2 [handlers] keys=hd1,hd2 [formatters] keys=fmt1,fmt2 #root logger # #level: DEBUG, INFO, WARN, ERROR, CRITICAL , NOTSET. # 在root logger, NOTSET 表示记录所有信息. #propagate 表示该logger是否从父logger中传送handler # channel 表示logger内通道名最低的部分,如 logger 名 "a.b.c", 该值是 "c". # #parent 表示父 logger名,但root的父log是 "(root)" 而不是 "root". # #qualname 完全的通道名 ,如logger 名是 "a.b.c", 该值即 "a.b.c". # #handlers 是本logger附带的逗号隔开的操作者名 #qualname=(root)用于root #propagate=1 用于非root的loggers [logger_root] level=NOTSET handlers=hd1 qualname=(root) propagate=1 channel= parent= #如果是NOTSET,表示查看父logger #propagate=0表示当root,1表示继承父logger [logger_modlog1] level=DEBUG propagate=1 qualname=modlog1 handlers=hd2 channel=modlog1 parent=(root) [logger_modlog2] level=WARN propagate=1 qualname=modlog1.modlog2 handlers=hd2 channel=modlog2 parent=modlog1 #NOTSET从父logger继承 #formatter留空表示logging._defaultFormatter [handler_hd1] class=StreamHandler level=DEBUG formatter=fmt1 args=(sys.stdout,) stream=sys.stdout [handler_hd2] class=FileHandler level=DEBUG formatter=fmt2 args=('python.log', 'w') filename=python.log mode=w [formatter_fmt1] format=F1 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_fmt2] format=F2 %(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s datefmt=


 

执行后,命令行看到输出:

  1. zhouhh@zhouhh-home:~$ python testlog.py  
  2. F1 2010-03-20 16:36:28,411 DEBUG log1调试信息  
  3. F1 2010-03-20 16:36:28,412 WARNING log1警告信息  
  4. F1 2010-03-20 16:36:28,412 ERROR log1 error错误信息  
  5. F1 2010-03-20 16:36:28,412 WARNING log2警告信息  
  6. F1 2010-03-20 16:36:28,412 ERROR log2 错误信息  
zhouhh@zhouhh-home:~$ python testlog.py F1 2010-03-20 16:36:28,411 DEBUG log1调试信息 F1 2010-03-20 16:36:28,412 WARNING log1警告信息 F1 2010-03-20 16:36:28,412 ERROR log1 error错误信息 F1 2010-03-20 16:36:28,412 WARNING log2警告信息 F1 2010-03-20 16:36:28,412 ERROR log2 错误信息


文件python.log看到信息:

  1. F2 2010-03-20 16:36:28,411 testlog.py(16): DEBUG log1调试信息  
  2. F2 2010-03-20 16:36:28,412 testlog.py(17): WARNING log1警告信息  
  3. F2 2010-03-20 16:36:28,412 testlog.py(18): ERROR log1 error错误信息  
  4. F2 2010-03-20 16:36:28,412 testlog.py(22): WARNING log2警告信息  
  5. F2 2010-03-20 16:36:28,412 testlog.py(22): WARNING log2警告信息  
  6. F2 2010-03-20 16:36:28,412 testlog.py(23): ERROR log2 错误信息  
  7. F2 2010-03-20 16:36:28,412 testlog.py(23): ERROR log2 错误信息  
F2 2010-03-20 16:36:28,411 testlog.py(16): DEBUG log1调试信息 F2 2010-03-20 16:36:28,412 testlog.py(17): WARNING log1警告信息 F2 2010-03-20 16:36:28,412 testlog.py(18): ERROR log1 error错误信息 F2 2010-03-20 16:36:28,412 testlog.py(22): WARNING log2警告信息 F2 2010-03-20 16:36:28,412 testlog.py(22): WARNING log2警告信息 F2 2010-03-20 16:36:28,412 testlog.py(23): ERROR log2 错误信息 F2 2010-03-20 16:36:28,412 testlog.py(23): ERROR log2 错误信息


 

下面是一个比较完全的配置文件,从拿过来的,功写logconf文件时参考:

  1. # --- logconf.ini -----------------------------------------------------------  
  2. #The "loggers" section contains the key names for all the loggers in this  
  3. #configuration. These are not the actual channel names, but values used to  
  4. #identify where the parameters for each logger are found in this file.  
  5. #The section for an individual logger is named "logger_xxx" where the "key"  
  6. #for a logger is "xxx". So ... "logger_root", "logger_log02", etc. further  
  7. #down the file, indicate how the root logger is set up, logger "log_02" is set  
  8. #up, and so on.  
  9. #Logger key names can be any identifier, except "root" which is reserved for  
  10. #the root logger. (The names "lognn" are generated by the GUI configurator.)   
  11. [loggers]  
  12. keys=root,log02,log03,log04,log05,log06,log07  
  13. #The "handlers" section contains the key names for all the handlers in this  
  14. #configuration. Just as for loggers above, the key names are values used to  
  15. #identify where the parameters for each handler are found in this file.  
  16. #The section for an individual handler is named "handler_xxx" where the "key"  
  17. #for a handler is "xxx". So sections "handler_hand01", "handler_hand02", etc.  
  18. #further down the file, indicate how the handlers "hand01", "hand02" etc.  
  19. #are set up.  
  20. #Handler key names can be any identifier. (The names "handnn" are generated  
  21. #by the GUI configurator.)   
  22. [handlers]  
  23. keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09  
  24. #The "formatters" section contains the key names for all the formatters in  
  25. #this configuration. Just as for loggers and handlers above, the key names  
  26. #are values used to identify where the parameters for each formatter are found  
  27. #in this file.  
  28. #The section for an individual formatter is named "formatter_xxx" where the  
  29. #"key" for a formatter is "xxx". So sections "formatter_form01",  
  30. #"formatter_form02", etc. further down the file indicate how the formatters  
  31. #"form01", "form02" etc. are set up.  
  32. #Formatter key names can be any identifier. (The names "formnn" are generated  
  33. #by the GUI configurator.)   
  34. [formatters]  
  35. keys=form01,form02,form03,form04,form05,form06,form07,form08,form09  
  36. #The section below indicates the information relating to the root logger.  
  37. #  
  38. #The level value needs to be one of DEBUG, INFO, WARN, ERROR, CRITICAL or NOTSET.  
  39. #In the root logger, NOTSET indicates that all messages will be logged.  
  40. #Level values are eval()'d in the context of the logging package's namespace.  
  41. #  
  42. #The propagate value indicates whether or not parents of this loggers will  
  43. #be traversed when looking for handlers. It doesn't really make sense in the  
  44. #root logger - it's just there because a root logger is almost like any other  
  45. #logger.  
  46. #  
  47. #The channel value indicates the lowest portion of the channel name of the  
  48. #logger. For a logger called "a.b.c", this value would be "c".  
  49. #  
  50. #The parent value indicates the key name of the parent logger, except that  
  51. #root is shown as "(root)" rather than "root".  
  52. #  
  53. #The qualname value is the fully qualified channel name of the logger. For a  
  54. #logger called "a.b.c", this value would be "a.b.c".  
  55. #  
  56. #The handlers value is a comma-separated list of the key names of the handlers  
  57. #attached to this logger.  
  58. #   
  59. [logger_root]  
  60. level=NOTSET  
  61. handlers=hand01  
  62. qualname=(root) # note - this is used in non-root loggers  
  63. propagate=1 # note - this is used in non-root loggers  
  64. channel=  
  65. parent=  
  66. #  
  67. #The explanation for the values in this section is analogous to the above. The  
  68. #logger is named "log02" and coincidentally has a key name of "log02". It has  
  69. #a level of DEBUG and handler with key name "hand02". (See section  
  70. #"handler_hand02" for handler details.) If the level value were NOTSET, this tells  
  71. #the logging package to consult the parent (as long as propagate is 1) for the  
  72. #effective level of this logger. If propagate is 0, this level is treated as for  
  73. #the root logger - a value of NOTSET means "pass everything", and other values are  
  74. #interpreted at face value.  
  75. #   
  76. [logger_log02]  
  77. level=DEBUG  
  78. propagate=1  
  79. qualname=log02  
  80. handlers=hand02  
  81. channel=log02  
  82. parent=(root)  
  83. #  
  84. #The explanation for the values in this section is analogous to the above. The  
  85. #logger is named "log02.log03" and has a key name of "log03".  
  86. #It has a level of INFO and handler with key name "hand03".  
  87. #   
  88. [logger_log03]  
  89. level=INFO  
  90. propagate=1  
  91. qualname=log02.log03  
  92. handlers=hand03  
  93. channel=log03  
  94. parent=log02  
  95. #  
  96. #The explanations for the values in this section and subsequent logger sections  
  97. #are analogous to the above.  
  98. #   
  99. [logger_log04]  
  100. level=WARN  
  101. propagate=0  
  102. qualname=log02.log03.log04  
  103. handlers=hand04  
  104. channel=log04  
  105. parent=log03  
  106. [logger_log05]  
  107. level=ERROR  
  108. propagate=1  
  109. qualname=log02.log03.log04.log05  
  110. handlers=hand05  
  111. channel=log05  
  112. parent=log04  
  113. [logger_log06]  
  114. level=CRITICAL  
  115. propagate=1  
  116. qualname=log02.log03.log04.log05.log06  
  117. handlers=hand06  
  118. channel=log06  
  119. parent=log05  
  120. [logger_log07]  
  121. level=WARN  
  122. propagate=1  
  123. qualname=log02.log03.log04.log05.log06.log07  
  124. handlers=hand07  
  125. channel=log07  
  126. parent=log06  
  127. #The section below indicates the information relating to handler "hand01".  
  128. #The first three keys (class, level and formatter) are common to all handlers.  
  129. #Any other values are handler-specific, except that "args", when eval()'ed,  
  130. #is the list of arguments to the constructor for the handler class.  
  131. #  
  132. #The class value indicates the handler's class (as determined by eval() in  
  133. #the logging package's namespace).  
  134. #  
  135. #The level value needs to be one of DEBUG, INFO, WARN, ERROR, CRITICAL or NOTSET.  
  136. #NOTSET means "use the parent's level".  
  137. #  
  138. #The formatter value indicates the key name of the formatter for this handler.  
  139. #If blank, a default formatter (logging._defaultFormatter) is used.  
  140. #  
  141. #The stream value indicates the stream for this StreamHandler. It is computed  
  142. #by doing eval() on the string value in the context of the logging package's  
  143. #namespace.  
  144. #  
  145. #The args value is a tuple of arguments which is passed to the constructor for  
  146. #this handler's class in addition to the "self" argument.  
  147. #   
  148. [handler_hand01]  
  149. class=StreamHandler  
  150. level=NOTSET  
  151. formatter=form01  
  152. args=(sys.stdout,)  
  153. stream=sys.stdout  
  154. #The section below indicates the information relating to handler "hand02".  
  155. #The first three keys are common to all handlers.  
  156. #Any other values are handler-specific, except that "args", when eval()'ed,  
  157. #is the list of arguments to the constructor for the handler class.  
  158. #  
  159. #The filename value is the name of the file to write logging information to.  
  160. #The mode value is the mode used to open() the file. The maxsize and backcount  
  161. #values control rollover as described in the package's API documentation.  
  162. #   
  163. [handler_hand02]  
  164. class=FileHandler  
  165. level=DEBUG  
  166. formatter=form02  
  167. args=('python.log''w')  
  168. filename=python.log  
  169. mode=w  
  170. #The section below indicates the information relating to handler "hand03".  
  171. #The first three keys are common to all handlers.  
  172. #Any other values are handler-specific, except that "args", when eval()'ed,  
  173. #is the list of arguments to the constructor for the handler class.  
  174. #  
  175. #The host value is the name of the host to send logging information to.  
  176. #The port value is the port number to use for the socket connection.  
  177. #   
  178. [handler_hand03]  
  179. class=handlers.SocketHandler  
  180. level=INFO  
  181. formatter=form03  
  182. args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)  
  183. host=localhost  
  184. port=DEFAULT_TCP_LOGGING_PORT  
  185. #The section below indicates the information relating to handler "hand04".  
  186. #The first three keys are common to all handlers.  
  187. #Any other values are handler-specific, except that "args", when eval()'ed,  
  188. #is the list of arguments to the constructor for the handler class.  
  189. #  
  190. #The host value is the name of the host to send logging information to.  
  191. #The port value is the port number to use for the socket connection.  
  192. #   
  193. [handler_hand04]  
  194. class=handlers.DatagramHandler  
  195. level=WARN  
  196. formatter=form04  
  197. args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)  
  198. host=localhost  
  199. port=DEFAULT_UDP_LOGGING_PORT  
  200. #The section below indicates the information relating to handler "hand05".  
  201. #The first three keys are common to all handlers.  
  202. #Any other values are handler-specific, except that "args", when eval()'ed,  
  203. #is the list of arguments to the constructor for the handler class.  
  204. #  
  205. #The host value is the name of the host to send logging information to.  
  206. #The port value is the port number to use for the socket connection.  
  207. #The facility is the syslog facility to use for logging.  
  208. #   
  209. [handler_hand05]  
  210. class=handlers.SysLogHandler  
  211. level=ERROR  
  212. formatter=form05  
  213. args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)  
  214. host=localhost  
  215. port=SYSLOG_UDP_PORT  
  216. facility=LOG_USER  
  217. #The section below indicates the information relating to handler "hand06".  
  218. #The first three keys are common to all handlers.  
  219. #Any other values are handler-specific, except that "args", when eval()'ed,  
  220. #is the list of arguments to the constructor for the handler class.  
  221. #  
  222. #The appname value is the name of the application which appears in the  
  223. #NT event log.  
  224. #The dllname value is the pathname of a DLL to use for message definitions.  
  225. #The logtype is the type of NT event log to write to - Application, Security  
  226. #or System.  
  227. #   
  228. [handler_hand06]  
  229. class=NTEventLogHandler  
  230. level=CRITICAL  
  231. formatter=form06  
  232. args=('Python Application''''Application')  
  233. appname=Python Application  
  234. dllname=  
  235. logtype=Application  
  236. #The section below indicates the information relating to handler "hand07".  
  237. #The first three keys are common to all handlers.  
  238. #Any other values are handler-specific, except that "args", when eval()'ed,  
  239. #is the list of arguments to the constructor for the handler class.  
  240. #  
  241. #The host value is the name of the SMTP server to connect to.  
  242. #The port value is the port number to use for the SMTP connection.  
  243. #The from value is the "From" value in emails.  
  244. #The to value is a comma-separated list of email addresses.  
  245. #The subject value is the subject of the email.  
  246. #   
  247. [handler_hand07]  
  248. class=SMTPHandler  
  249. level=WARN  
  250. formatter=form07  
  251. args=('localhost''from@abc', ['user1@abc''user2@xyz'], 'Logger Subject')  
  252. host=localhost  
  253. port=25  
  254. from=from@abc  
  255. to=user1@abc,user2@xyz  
  256. subject=Logger Subject  
  257. #The section below indicates the information relating to handler "hand08".  
  258. #The first three keys are common to all handlers.  
  259. #Any other values are handler-specific, except that "args", when eval()'ed,  
  260. #is the list of arguments to the constructor for the handler class.  
  261. #  
  262. #The capacity value is the size of this handler's buffer.  
  263. #The flushlevel value is the logging level at which the buffer is flushed.  
  264. #The from value is the "From" value in emails.  
  265. #The target value is the key name of the handler which messages are flushed  
  266. #to (i.e. sent to when flushing).  
  267. #   
  268. [handler_hand08]  
  269. class=MemoryHandler  
  270. level=NOTSET  
  271. formatter=form08  
  272. target=  
  273. args=(10, ERROR)  
  274. capacity=10  
  275. flushlevel=ERROR  
  276. #The section below indicates the information relating to handler "hand09".  
  277. #The first three keys are common to all handlers.  
  278. #Any other values are handler-specific, except that "args", when eval()'ed,  
  279. #is the list of arguments to the constructor for the handler class.  
  280. #  
  281. #The host value is the name of the HTTP server to connect to.  
  282. #The port value is the port number to use for the HTTP connection.  
  283. #The url value is the url to request from the server.  
  284. #The method value is the HTTP request type (GET or POST).  
  285. #   
  286. [handler_hand09]  
  287. class=HTTPHandler  
  288. level=NOTSET  
  289. formatter=form09  
  290. args=('localhost:9022''/log''GET')  
  291. host=localhost  
  292. port=9022  
  293. url=/log  
  294. method=GET  
  295. #The sections below indicate the information relating to the various  
  296. #formatters. The format value is the overall format string, and the  
  297. #datefmt value is the strftime-compatible date/time format string. If  
  298. #empty, the logging package substitutes ISO8601 format date/times where  
  299. #needed. See the package API documentation for more details  
  300. #of the format string structure.  
  301. #   
  302. [formatter_form01]  
  303. format=F1 %(asctime)s %(levelname)s %(message)s  
  304. datefmt=  
  305. [formatter_form02]  
  306. format=F2 %(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s  
  307. datefmt=  
  308. [formatter_form03]  
  309. format=F3 %(asctime)s %(levelname)s %(message)s  
  310. datefmt=  
  311. [formatter_form04]  
  312. format=%(asctime)s %(levelname)s %(message)s  
  313. datefmt=  
  314. [formatter_form05]  
  315. format=F5 %(asctime)s %(levelname)s %(message)s  
  316. datefmt=  
  317. [formatter_form06]  
  318. format=F6 %(asctime)s %(levelname)s %(message)s  
  319. datefmt=  
  320. [formatter_form07]  
  321. format=F7 %(asctime)s %(levelname)s %(message)s  
  322. datefmt=  
  323. [formatter_form08]  
  324. format=F8 %(asctime)s %(levelname)s %(message)s  
  325. datefmt=  
  326. [formatter_form09]  
  327. format=F9 %(asctime)s %(levelname)s %(message)s  
  328. datefmt=  
  329. # --- end of logconf.ini ----------------------------------------------------  
# --- logconf.ini ----------------------------------------------------------- #The "loggers" section contains the key names for all the loggers in this #configuration. These are not the actual channel names, but values used to #identify where the parameters for each logger are found in this file. #The section for an individual logger is named "logger_xxx" where the "key" #for a logger is "xxx". So ... "logger_root", "logger_log02", etc. further #down the file, indicate how the root logger is set up, logger "log_02" is set #up, and so on. #Logger key names can be any identifier, except "root" which is reserved for #the root logger. (The names "lognn" are generated by the GUI configurator.) [loggers] keys=root,log02,log03,log04,log05,log06,log07 #The "handlers" section contains the key names for all the handlers in this #configuration. Just as for loggers above, the key names are values used to #identify where the parameters for each handler are found in this file. #The section for an individual handler is named "handler_xxx" where the "key" #for a handler is "xxx". So sections "handler_hand01", "handler_hand02", etc. #further down the file, indicate how the handlers "hand01", "hand02" etc. #are set up. #Handler key names can be any identifier. (The names "handnn" are generated #by the GUI configurator.) [handlers] keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 #The "formatters" section contains the key names for all the formatters in #this configuration. Just as for loggers and handlers above, the key names #are values used to identify where the parameters for each formatter are found #in this file. #The section for an individual formatter is named "formatter_xxx" where the #"key" for a formatter is "xxx". So sections "formatter_form01", #"formatter_form02", etc. further down the file indicate how the formatters #"form01", "form02" etc. are set up. #Formatter key names can be any identifier. (The names "formnn" are generated #by the GUI configurator.) [formatters] keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 #The section below indicates the information relating to the root logger. # #The level value needs to be one of DEBUG, INFO, WARN, ERROR, CRITICAL or NOTSET. #In the root logger, NOTSET indicates that all messages will be logged. #Level values are eval()'d in the context of the logging package's namespace. # #The propagate value indicates whether or not parents of this loggers will #be traversed when looking for handlers. It doesn't really make sense in the #root logger - it's just there because a root logger is almost like any other #logger. # #The channel value indicates the lowest portion of the channel name of the #logger. For a logger called "a.b.c", this value would be "c". # #The parent value indicates the key name of the parent logger, except that #root is shown as "(root)" rather than "root". # #The qualname value is the fully qualified channel name of the logger. For a #logger called "a.b.c", this value would be "a.b.c". # #The handlers value is a comma-separated list of the key names of the handlers #attached to this logger. # [logger_root] level=NOTSET handlers=hand01 qualname=(root) # note - this is used in non-root loggers propagate=1 # note - this is used in non-root loggers channel= parent= # #The explanation for the values in this section is analogous to the above. The #logger is named "log02" and coincidentally has a key name of "log02". It has #a level of DEBUG and handler with key name "hand02". (See section #"handler_hand02" for handler details.) If the level value were NOTSET, this tells #the logging package to consult the parent (as long as propagate is 1) for the #effective level of this logger. If propagate is 0, this level is treated as for #the root logger - a value of NOTSET means "pass everything", and other values are #interpreted at face value. # [logger_log02] level=DEBUG propagate=1 qualname=log02 handlers=hand02 channel=log02 parent=(root) # #The explanation for the values in this section is analogous to the above. The #logger is named "log02.log03" and has a key name of "log03". #It has a level of INFO and handler with key name "hand03". # [logger_log03] level=INFO propagate=1 qualname=log02.log03 handlers=hand03 channel=log03 parent=log02 # #The explanations for the values in this section and subsequent logger sections #are analogous to the above. # [logger_log04] level=WARN propagate=0 qualname=log02.log03.log04 handlers=hand04 channel=log04 parent=log03 [logger_log05] level=ERROR propagate=1 qualname=log02.log03.log04.log05 handlers=hand05 channel=log05 parent=log04 [logger_log06] level=CRITICAL propagate=1 qualname=log02.log03.log04.log05.log06 handlers=hand06 channel=log06 parent=log05 [logger_log07] level=WARN propagate=1 qualname=log02.log03.log04.log05.log06.log07 handlers=hand07 channel=log07 parent=log06 #The section below indicates the information relating to handler "hand01". #The first three keys (class, level and formatter) are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The class value indicates the handler's class (as determined by eval() in #the logging package's namespace). # #The level value needs to be one of DEBUG, INFO, WARN, ERROR, CRITICAL or NOTSET. #NOTSET means "use the parent's level". # #The formatter value indicates the key name of the formatter for this handler. #If blank, a default formatter (logging._defaultFormatter) is used. # #The stream value indicates the stream for this StreamHandler. It is computed #by doing eval() on the string value in the context of the logging package's #namespace. # #The args value is a tuple of arguments which is passed to the constructor for #this handler's class in addition to the "self" argument. # [handler_hand01] class=StreamHandler level=NOTSET formatter=form01 args=(sys.stdout,) stream=sys.stdout #The section below indicates the information relating to handler "hand02". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The filename value is the name of the file to write logging information to. #The mode value is the mode used to open() the file. The maxsize and backcount #values control rollover as described in the package's API documentation. # [handler_hand02] class=FileHandler level=DEBUG formatter=form02 args=('python.log', 'w') filename=python.log mode=w #The section below indicates the information relating to handler "hand03". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The host value is the name of the host to send logging information to. #The port value is the port number to use for the socket connection. # [handler_hand03] class=handlers.SocketHandler level=INFO formatter=form03 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) host=localhost port=DEFAULT_TCP_LOGGING_PORT #The section below indicates the information relating to handler "hand04". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The host value is the name of the host to send logging information to. #The port value is the port number to use for the socket connection. # [handler_hand04] class=handlers.DatagramHandler level=WARN formatter=form04 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) host=localhost port=DEFAULT_UDP_LOGGING_PORT #The section below indicates the information relating to handler "hand05". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The host value is the name of the host to send logging information to. #The port value is the port number to use for the socket connection. #The facility is the syslog facility to use for logging. # [handler_hand05] class=handlers.SysLogHandler level=ERROR formatter=form05 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) host=localhost port=SYSLOG_UDP_PORT facility=LOG_USER #The section below indicates the information relating to handler "hand06". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The appname value is the name of the application which appears in the #NT event log. #The dllname value is the pathname of a DLL to use for message definitions. #The logtype is the type of NT event log to write to - Application, Security #or System. # [handler_hand06] class=NTEventLogHandler level=CRITICAL formatter=form06 args=('Python Application', '', 'Application') appname=Python Application dllname= logtype=Application #The section below indicates the information relating to handler "hand07". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The host value is the name of the SMTP server to connect to. #The port value is the port number to use for the SMTP connection. #The from value is the "From" value in emails. #The to value is a comma-separated list of email addresses. #The subject value is the subject of the email. # [handler_hand07] class=SMTPHandler level=WARN formatter=form07 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') host=localhost port=25 from=from@abc to=user1@abc,user2@xyz subject=Logger Subject #The section below indicates the information relating to handler "hand08". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The capacity value is the size of this handler's buffer. #The flushlevel value is the logging level at which the buffer is flushed. #The from value is the "From" value in emails. #The target value is the key name of the handler which messages are flushed #to (i.e. sent to when flushing). # [handler_hand08] class=MemoryHandler level=NOTSET formatter=form08 target= args=(10, ERROR) capacity=10 flushlevel=ERROR #The section below indicates the information relating to handler "hand09". #The first three keys are common to all handlers. #Any other values are handler-specific, except that "args", when eval()'ed, #is the list of arguments to the constructor for the handler class. # #The host value is the name of the HTTP server to connect to. #The port value is the port number to use for the HTTP connection. #The url value is the url to request from the server. #The method value is the HTTP request type (GET or POST). # [handler_hand09] class=HTTPHandler level=NOTSET formatter=form09 args=('localhost:9022', '/log', 'GET') host=localhost port=9022 url=/log method=GET #The sections below indicate the information relating to the various #formatters. The format value is the overall format string, and the #datefmt value is the strftime-compatible date/time format string. If #empty, the logging package substitutes ISO8601 format date/times where #needed. See the package API documentation for more details #of the format string structure. # [formatter_form01] format=F1 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_form02] format=F2 %(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s datefmt= [formatter_form03] format=F3 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_form04] format=%(asctime)s %(levelname)s %(message)s datefmt= [formatter_form05] format=F5 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_form06] format=F6 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_form07] format=F7 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_form08] format=F8 %(asctime)s %(levelname)s %(message)s datefmt= [formatter_form09] format=F9 %(asctime)s %(levelname)s %(message)s datefmt= # --- end of logconf.ini ----------------------------------------------------


 

3.参考:

http://www.python.org/dev/peps/pep-0282/

http://blog.donews.com/limodou/archive/2005/02/16/278699.aspx

阅读(6782) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~