python的logging模块总结:
1 #!/usr/bin/python 2 #encoding=utf-8 3 4 import logging 5 6 logging.basicConfig(level=logging.DEBUG, 7 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 8 datefmt='%a, %d %b %Y %H:%M:%S', 9 filename='MYTEST.log', filemode='w') 10 11 #定义一个StreamHandler 12 console = logging.StreamHandler() 13 console.setLevel(logging.INFO) 14 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') 15 console.setFormatter(formatter) 16 logging.getLogger('').addHandler(console) 17 18 from logging.handlers import RotatingFileHandler 19 #日志回滚handler 20 Rthandler = RotatingFileHandler('MYTEST.log', maxBytes=10*1024*1024, backupCount=5) 21 Rthandler.setLevel(logging.INFO) 22 formatter = logging.Formatter('%s(name)-12s: %(levelname)-8s %(message)s') 23 Rthandler.setFormatter(formatter) 24 logging.getLogger('').addHandler(Rthandler) 25 26 logging.debug("debgu message") 27 logging.info("info mesg") 28 logging.warning("warning msg") 29 30 #通过logging.conf模块配置日志 31 #logger.conf 32 """ 33 [loggers] 34 keys=root, TEST1, TEST2 #TEST1, TEST2 35 [logger_root] 36 level=DEBUG 37 handlers = HANDLER1, HANDLER2 38 [logger_TEST1] 39 handlers = HANDLER1, HANDLER2 40 qualname=TEST1 41 progate = 0 42 [logger_TEST2] 43 handlers = HANDLER1, HANDLER2 44 qualname=TEST2 45 progate = 0 46 ######################################### 47 [handlers] 48 keys=hand01,hand02,hand03 49 [handler_hand01] 50 class=StreamHandler 51 level=INFO 52 formatter=form02 53 args=(sys.stderr,) 54 [handler_hand02] 55 class=FileHandler 56 level=DEBUG 57 formatter=form01 58 level=DEBUG 59 formatter=form01 60 args=('myapp.log', 'a') 61 [handler_hand03] 62 class=handlers.RotatingFileHandler 63 level=INFO 64 formatter=form02 65 args=('myapp.log', 'a', 10*1024*1024, 5) 66 ############################################### 67 [formatters] 68 keys=form01,form02 69 [formatter_form01] 70 format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s 71 datefmt=%a, %d %b %Y %H:%M:%S 72 [formatter_form02] 73 format=%(name)-12s: %(levelname)-8s %(message)s 74 datefmt=%a, %d %b %Y %H:%M:%S 75 """ 76 import logging 77 import logging.config 78 79 logging.config.fileConfig("logger.conf") 80 logger = logging.getLogger("example01") 81 82 logger.debug('This is debug message') 83 logger.info('This is info message') 84 logger.warning('This is warning message')