国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解python之配置日志的幾種方式

2020-02-16 01:33:42
字體:
供稿:網(wǎng)友

作為開發(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=            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 罗山县| 杭州市| 平遥县| 资兴市| 白水县| 石狮市| 乐业县| 海兴县| 江川县| 永吉县| 神池县| 五寨县| 耒阳市| 民丰县| 神池县| 嵩明县| 仙游县| 绥滨县| 万源市| 巩义市| 汝城县| 盐亭县| 辽宁省| 长兴县| 九江市| 宜都市| 鄯善县| 龙胜| 满洲里市| 天峨县| 临安市| 广昌县| 宁阳县| 会理县| 额尔古纳市| 汽车| 揭西县| 吴川市| 西乌珠穆沁旗| 平武县| 双江|