国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 哈密市| 红桥区| 翁源县| 额尔古纳市| 油尖旺区| 洞头县| 南木林县| 甘德县| 双鸭山市| 潮安县| 五指山市| 安多县| 渭南市| 皋兰县| 青海省| 英吉沙县| 称多县| 中方县| 林州市| 塘沽区| 谷城县| 肇庆市| 高青县| 册亨县| 明星| 惠东县| 仁化县| 灵宝市| 宁乡县| 小金县| 六盘水市| 新和县| 理塘县| 凉城县| 那曲县| 泰兴市| 汉源县| 道真| 元朗区| 道真| 晋州市|