国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python 實(shí)現(xiàn)logging動(dòng)態(tài)變更輸出日志文件名

瀏覽:3日期:2022-06-25 08:05:58

python作為一門非常容易上手的腳本語言,日志輸出更是簡(jiǎn)單,logging模塊,簡(jiǎn)單的設(shè)置配置和屬性,就能實(shí)現(xiàn)到控制臺(tái)輸出日志,在basicConfig()設(shè)置文件名,就能夠?qū)⑷罩拘畔懭胛募?jiǎn)直是簡(jiǎn)單到不能再簡(jiǎn)單。

最近在項(xiàng)目中就遇到一個(gè)日志問題,使用python編寫的服務(wù)程序一直運(yùn)行,連續(xù)處理一些任務(wù),每個(gè)任務(wù)的關(guān)鍵信息都需要輸出到文件中,便于維護(hù)人員查看,可是對(duì)于簡(jiǎn)單實(shí)用logging來說,日志寫入文件非常簡(jiǎn)單,由于服務(wù)程序連續(xù)運(yùn)行,一直向一個(gè)文件記錄日志信息有些不妥,有常識(shí)的開發(fā)人員都知道,長(zhǎng)時(shí)間的日志輸出會(huì)導(dǎo)致日志文件過大,可是如何在服務(wù)運(yùn)行時(shí),修改日志的輸出文件,以當(dāng)天日期作為日志文件名。

代碼編寫環(huán)境:python3.4.3

1.logging.basicConfig()

首先,想到的是更改logging.basicConfig(filename=logfilename)參數(shù),來實(shí)現(xiàn)變更日志文件名的目的。編寫代碼如下:

log_fmt = ’%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s’for i in range(1,4): filename = str.format(’mylog%d.txt’ % i) logging.basicConfig(format=log_fmt, level=logging.DEBUG, filename=filename) logging.debug(’This is debug message’) logging.info(’This is info message’) logging.warning(’This is warning message’)

運(yùn)行結(jié)果沒有達(dá)到預(yù)期的效果,只有日志文件mylog1.txt被創(chuàng)建,mylog2.txt和mylog3.txt都未被創(chuàng)建,連續(xù)3次的輸出的內(nèi)容都寫入mylog1.txt中。說明logging.basicConfig()設(shè)置屬性具有全局性,第一次設(shè)置之后,之后再設(shè)置將不再生效。查看官方文檔,也確實(shí)是如此。

logging.basicConfig(**kwargs)

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

This function does nothing if the root logger already has handlers configured for it.

此路不通,只好用其他方法。

2.Handler對(duì)象

logging支持添加多個(gè)不同類型的handler對(duì)象,實(shí)現(xiàn)對(duì)控制臺(tái)(logging.StreamHandler)、文件(logging.FileHandler)等不同目標(biāo)輸出日志。

logging支持的日志詳情見文檔logging.handlers

通過增加多個(gè)handler對(duì)象,可是實(shí)現(xiàn)同時(shí)在控制臺(tái)、文件同時(shí)輸出不同級(jí)別的日志信息。

# 默認(rèn)配置logging寫入本地文件logging.basicConfig(level=logging.DEBUG, format=’%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s’, datefmt=’%a, %d %b %Y %H:%M:%S’, filename=’myapp2.log’, filemode=’w’)#定義一個(gè)StreamHandler,將INFO級(jí)別或更高的日志信息打印到標(biāo)準(zhǔn)錯(cuò)誤,并將其添加到當(dāng)前的日志處理對(duì)象。console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter(’%(name)-12s: %(levelname)-8s %(message)s’)console.setFormatter(formatter)logging.getLogger(’’).addHandler(console)logging.debug(’This is debug message’)logging.info(’This is info message’)logging.warning(’This is warning message’)

考慮實(shí)現(xiàn)簡(jiǎn)單又能說明效果,寫入文件使用logging.basicConfig()設(shè)置,并添加輸出指向控制臺(tái)的流處理(StreamHandler)對(duì)象console,實(shí)現(xiàn)同時(shí)輸出日志。當(dāng)然也可以反過來,默認(rèn)設(shè)置控制臺(tái)輸出日志,之后創(chuàng)建文件對(duì)象(logging.FileHandler),并加入處理集合,實(shí)現(xiàn)同樣的效果。

logging.getLogger(’’)獲取的是名為’root’的默認(rèn)根節(jié)點(diǎn)

同時(shí),logging提供addHandler()的方法,自然也會(huì)有管理handler的方法。

延伸之前Handler的思路,我們可以實(shí)現(xiàn)對(duì)handler的動(dòng)態(tài)管理,變更日志文件。每次需要變更輸出文件路徑前,使用handler管理清空原先的logging.FileHandler對(duì)象,重新創(chuàng)建一個(gè)新文件名的logging.FileHandler對(duì)象即可。

# 默認(rèn)配置logging寫入本地文件logging.basicConfig(level=logging.DEBUG, format=’%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s’, datefmt=’%a, %d %b %Y %H:%M:%S’, filename=’myapp2.log’, filemode=’w’)#定義一個(gè)StreamHandler,將INFO級(jí)別或更高的日志信息打印到標(biāo)準(zhǔn)錯(cuò)誤,并將其添加到當(dāng)前的日志處理對(duì)象。console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter(’%(name)-12s: %(levelname)-8s %(message)s’)console.setFormatter(formatter)logging.getLogger(’’).addHandler(console)logging.debug(’This is debug message’)logging.info(’This is info message’)logging.warning(’This is warning message’)

使用for循環(huán)執(zhí)行3次處理,分別創(chuàng)建日志文件名稱為mylog1.txt, mylog2.tx, mylog3.txt,并寫入相同的內(nèi)容。執(zhí)行結(jié)果確實(shí)產(chǎn)生不同名稱的文件,日志內(nèi)容也正確寫入。

至此,已經(jīng)實(shí)現(xiàn)動(dòng)態(tài)變更輸出文件日志名稱的功能。至于按照日志輸出文件名,只需要按照上述代碼的思路,將創(chuàng)建logging.FileHandler()的文件名參數(shù)變更就能達(dá)成目的。

簡(jiǎn)單實(shí)現(xiàn)方案

瀏覽官方文檔logging.handlers一節(jié)內(nèi)容,python考慮到日志的常規(guī)使用場(chǎng)景,已經(jīng)封裝更為簡(jiǎn)單的實(shí)現(xiàn)方案,TimedRotatingFileHandler,只需簡(jiǎn)單的配置,即可實(shí)現(xiàn)對(duì)輸出日志文件的基本管理,靈活易用,代碼如下:

import logging, logging.handlersimport time’’’TimedRotatingFileHandler構(gòu)造函數(shù)聲明class logging.handlers.TimedRotatingFileHandler(filename, when=’h’, interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)filename 日志文件名前綴when 日志名變更時(shí)間單位 ’S’ Seconds ’M’ Minutes ’H’ Hours ’D’ Days ’W0’-’W6’ Weekday (0=Monday) ’midnight’ Roll over at midnightinterval 間隔時(shí)間,是指等待N個(gè)when單位的時(shí)間后,自動(dòng)重建文件backupCount 保留日志最大文件數(shù),超過限制,刪除最先創(chuàng)建的文件;默認(rèn)值0,表示不限制。delay 延遲文件創(chuàng)建,直到第一次調(diào)用emit()方法創(chuàng)建日志文件atTime 在指定的時(shí)間(datetime.time格式)創(chuàng)建日志文件。’’’def test_TimedRotatingFileHandler(): # 定義日志輸出格式 fmt_str = ’%(asctime)s[level-%(levelname)s][%(name)s]:%(message)s’ # 初始化 logging.basicConfig() # 創(chuàng)建TimedRotatingFileHandler處理對(duì)象 # 間隔5(S)創(chuàng)建新的名稱為myLog%Y%m%d_%H%M%S.log的文件,并一直占用myLog文件。 fileshandle = logging.handlers.TimedRotatingFileHandler(’myLog’, when=’S’, interval=5, backupCount=3) # 設(shè)置日志文件后綴,以當(dāng)前時(shí)間作為日志文件后綴名。 fileshandle.suffix = '%Y%m%d_%H%M%S.log' # 設(shè)置日志輸出級(jí)別和格式 fileshandle.setLevel(logging.DEBUG) formatter = logging.Formatter(fmt_str) fileshandle.setFormatter(formatter) # 添加到日志處理對(duì)象集合 logging.getLogger(’’).addHandler(fileshandle)if __name__ == ’__main__’: test_TimedRotatingFileHandler() # 測(cè)試在200s內(nèi)創(chuàng)建文件多個(gè)日志文件 for i in range(0, 100): logging.debug('logging.debug') logging.info('logging.info') logging.warning('logging.warning') logging.error('logging.error') time.sleep(2)

補(bǔ)充:使用Python的logging.config.fileConfig配置日志

Python的logging.config.fileConfig方式配置日志,通過解析conf配置文件實(shí)現(xiàn)。文件 logglogging.conf 配置如下:

[loggers]keys=root,fileLogger,rotatingFileLogger [handlers]keys=consoleHandler,fileHandler,rotatingFileHandler [formatters]keys=simpleFormatter [logger_root]level=DEBUGhandlers=consoleHandler [logger_fileLogger]level=DEBUG# 該logger中配置的handlerhandlers=fileHandler# logger 的名稱qualname=fileLoggerpropagate=0 [logger_rotatingFileLogger]level=DEBUG# 這樣配置,rotatingFileLogger中就同時(shí)配置了consoleHandler,rotatingFileHandler# consoleHandler 負(fù)責(zé)將日志輸出到控制臺(tái)# rotatingFileHandler 負(fù)責(zé)將日志輸出保存到文件中handlers=consoleHandler,rotatingFileHandlerqualname=rotatingFileLoggerpropagate=0 [handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,) [handler_fileHandler]class=FileHandlerlevel=DEBUGformatter=simpleFormatterargs=(’logs/logging.log’, ’a’) [handler_rotatingFileHandler]class=handlers.RotatingFileHandlerlevel=WARNINGformatter=simpleFormatterargs=('logs/rotating_logging.log', 'a', 1*1024*1024, 5) [formatter_simpleFormatter]#format=%(asctime)s - %(name)s - %(levelname)s - %(message)sformat=%(asctime)s - %(module)s - %(thread)d - %(levelname)s : %(message)sdatefmt=%Y-%m-%d %H:%M:%S以上配置文件主要包含以下幾部分:

loggers : 配置logger信息。必須包含一個(gè)名字叫做root的logger,當(dāng)使用無參函數(shù)logging.getLogger()時(shí),默認(rèn)返回root這個(gè)logger,其他自定義logger可以通過 logging.getLogger('fileLogger') 方式進(jìn)行調(diào)用

handlers:定義聲明handlers信息。常用的handlers包括 StreamHandler(僅將日志輸出到kong控制臺(tái))、FileHandler(將日志信息輸出保存到文件)、RotaRotatingFileHandler(將日志輸出保存到文件中,并設(shè)置單個(gè)日志wenj文件的大小和日志文件個(gè)數(shù))

formatter : 設(shè)置日志格式

logger_xxx : 對(duì)loggers中聲明的logger進(jìn)行逐個(gè)配置,且要一一對(duì)應(yīng)

handler_xxx : 對(duì)handlers中聲明的handler進(jìn)行逐個(gè)配置,且要一一對(duì)應(yīng)

formatter_xxx : 對(duì)聲明的formatterjinx進(jìn)行配置

代碼示例

logging.config.fileConfig(“l(fā)ogging.conf”) # 輸出日志到控制臺(tái),獲取的是root對(duì)應(yīng)的loggerconsole_logger = logging.getLogger() # 輸出日志到單個(gè)文件file_logger = logging.getLogger(name='fileLogger') # rotatingFileLogger中額consoleHandler輸出到控制臺(tái),rotatingHandler輸出日志到文件rotating_logger = logging.getLogger(name='rotatingFileLogger')友情提示

進(jìn)行以上配置后,在項(xiàng)目中需要進(jìn)行日志輸出的地方通過logging.getLogger()方式就可以獲取到du應(yīng)的logger,然后就可以使用logger.info('xxx')jinx進(jìn)行日志輸出了。

使用這種方式配置日志,一定要在項(xiàng)目的入口函數(shù)中就調(diào)用 logging.config.fileConfig(“l(fā)ogging.conf”)函數(shù),因?yàn)?logging.conf 文件中,在handler中配置的是日志文件的相對(duì)地址,如果在其他代碼文件中進(jìn)行調(diào)用,由于相對(duì)地址的原因,將導(dǎo)致日志文件會(huì)出現(xiàn)在yixi意想不到的位置。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 嫩江县| 涟源市| 鸡东县| 启东市| 惠水县| 定西市| 桐梓县| 东兰县| 康定县| 合肥市| 吴忠市| 荥阳市| 布拖县| 岚皋县| 泰来县| 漠河县| 太仆寺旗| 瑞昌市| 呼伦贝尔市| 任丘市| 五峰| 蓝田县| 临澧县| 密云县| 延安市| 新闻| 泊头市| 巴彦县| 平远县| 德化县| 长沙县| 茂名市| 汶上县| 普洱| 博野县| 交口县| 高平市| 南涧| 象山县| 磐石市| 金沙县|