作為開發(fā)者,我們可以通過以下3中方式來配置logging:
1)使用Python代碼顯式的創(chuàng)建loggers, handlers和formatters并分別調(diào)用它們的配置函數(shù);
2)創(chuàng)建一個日志配置文件,然后使用fileConfig()函數(shù)來讀取該文件的內(nèi)容;
3)創(chuàng)建一個包含配置信息的dict,然后把它傳遞個dictConfig()函數(shù);
需要說明的是,logging.basicConfig()也屬于第一種方式,它只是對loggers, handlers和formatters的配置函數(shù)進行了封裝。另外,第二種配置方式相對于第一種配置方式的優(yōu)點在于,它將配置信息和代碼進行了分離,這一方面降低了日志的維護成本,同時還使得非開發(fā)人員也能夠去很容易地修改日志配置。
一、使用Python代碼實現(xiàn)日志配置
代碼如下:
# 創(chuàng)建一個日志器logger并設(shè)置其日志級別為DEBUGlogger = logging.getLogger('simple_logger')logger.setLevel(logging.DEBUG)# 創(chuàng)建一個流處理器handler并設(shè)置其日志級別為DEBUGhandler = logging.StreamHandler(sys.stdout)handler.setLevel(logging.DEBUG)# 創(chuàng)建一個格式器formatter并將其添加到處理器handlerformatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")handler.setFormatter(formatter)# 為日志器logger添加上面創(chuàng)建的處理器handlerlogger.addHandler(handler)# 日志輸出logger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')運行輸出:
2017-05-15 11:30:50,955 - simple_logger - DEBUG - debug message2017-05-15 11:30:50,955 - simple_logger - INFO - info message2017-05-15 11:30:50,955 - simple_logger - WARNING - warn message2017-05-15 11:30:50,955 - simple_logger - ERROR - error message2017-05-15 11:30:50,955 - simple_logger - CRITICAL - critical message
二、使用配置文件和fileConfig()函數(shù)實現(xiàn)日志配置
現(xiàn)在我們通過配置文件的方式來實現(xiàn)與上面同樣的功能:
# 讀取日志配置文件內(nèi)容logging.config.fileConfig('logging.conf')# 創(chuàng)建一個日志器loggerlogger = logging.getLogger('simpleExample')# 日志輸出logger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')配置文件logging.conf內(nèi)容如下:
[loggers]keys=root,simpleExample[handlers]keys=fileHandler,consoleHandler[formatters]keys=simpleFormatter[logger_root]level=DEBUGhandlers=fileHandler[logger_simpleExample]level=DEBUGhandlers=consoleHandlerqualname=simpleExamplepropagate=0[handler_consoleHandler]class=StreamHandlerargs=(sys.stdout,)level=DEBUGformatter=simpleFormatter[handler_fileHandler]class=FileHandlerargs=('logging.log', 'a')level=ERRORformatter=simpleFormatter[formatter_simpleFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt=            
| 
 
 | 
新聞熱點
疑難解答