python將logging模塊封裝成單獨模塊并實現(xiàn)動態(tài)切換Level方式
查找了很多資料,但網(wǎng)上給出的教程都是大同小異的,而我想將代碼進(jìn)一步精簡,解耦,想實現(xiàn)如下兩個目標(biāo)
1. 將logging模塊的初始化,配置,設(shè)置等代碼封裝到一個模塊中;
2. 能根據(jù)配置切換logging.level, 網(wǎng)上給出的教程都是寫死的,如果我在線上之前使用了logging.info(msg),現(xiàn)在想切換為logging.debug(msg)怎么辦?需要能夠根據(jù)配置文件中的 設(shè)置配置logging.level
兩個文件:
logging_class:將logging模塊的初始化,配置,設(shè)置等代碼封裝到一此模塊中,讀取配置文件中對于log等級的設(shè)置項;需要使用log功能的模塊import 這個模塊
applogconfig.ini: 配置文件
logging_class:
import logging
import sys
import ConfigParser
def log_building(log_file):
try:
#set format
format_str=logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s")
#create stander output handler
crit_hand=logging.StreamHandler(sys.stderr)
crit_hand.setFormatter(format_str)
#create file handler
file_hand=logging.FileHandler(log_file,'a')
file_hand.setFormatter(format_str)
app_log=logging.getLogger(__name__)
app_log.addHandler(crit_hand)
app_log.addHandler(file_hand)
#必須設(shè)置,否則無法輸出
app_log.setLevel(logging.NOTSET)
return app_log
except Exception as e:
logging.shutdown()
raise e
def config_file_get(fpath):
try:
cnf_dict={}
cfg=ConfigParser.SafeConfigParser()
cfg.read(fpath)
for section in cfg.sections():
#將ini中的item組合到字典中,key=section+_option
for item in cfg.items(section):
key= section+'_'+item[0]
value=item[1]
if cnf_dict.get(key,None)==None:
cnf_dict[key]=value
return cnf_dict
except Exception as e:
raise e
def log_level_get(level):
DEBUG_LEVEL={'CRITICAL':logging.CRITICAL,'ERROR':logging.ERROR,'WARNING':logging.WARNING,
'INFO':logging.INFO,'DEBUG':logging.DEBUG
}
try:
return DEBUG_LEVEL.get(level.upper())
except Exception as e:
raise e
applogconfig.ini內(nèi)容:
[log] log_level=ERROR dir=log
以下為unittest內(nèi)容:
import unittest
import logging_class
import os
import logging
class Test(unittest.TestCase):
cfg={}
def setUp(self):
print 'test begin'
self.cfg={}
def tearDown(self):
print 'test end'
def testlog_level_get(self):
currentWorkingPath = r'E:\Myworkspace\python\logging_module\logging_module'
ini_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'applogconfig.ini')))
self.cfg=logging_class.config_file_get(ini_file)
self.assertEqual(self.cfg['log_log_level'].upper(), 'ERROR', 'OK')
def testlog_level_set(self):
currentWorkingPath = r'E:\Myworkspace\python\logging_module\logging_module'
ini_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'applogconfig.ini')))
self.cfg=logging_class.config_file_get(ini_file)
#print self.cfg['log_log_level']
self.assertEqual(logging_class.log_level_get(self.cfg['log_log_level']), logging.ERROR, 'OK')
def testlog_building(self):
currentWorkingPath = r'E:\Myworkspace\python\logging_module\logging_module'
ini_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'applogconfig.ini')))
log_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'b.log')))
self.cfg=logging_class.config_file_get(ini_file)
#print self.cfg['log_log_level']
level=logging_class.log_level_get(self.cfg['log_log_level'])
log=logging_class.log_building(log_file)
log.log(level, 'dddds')
log.debug('msg')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
輸出:
Finding files... done. Importing test modules ... done. test begin test end test begin test end test begin 2016-12-15 17:59:04,059 logging_module_test.py[line:48] ERROR dddds test end ---------------------------------------------------------------------- Ran 3 tests in 0.004s
補充知識:一種logging封裝方法,不會產(chǎn)生重復(fù)log
在調(diào)試logging的封裝的時候,發(fā)現(xiàn)已經(jīng)調(diào)用了logging封裝的函數(shù),在被其它函數(shù)再調(diào)用時,會出現(xiàn)重復(fù)的logging。原因是不同的地方創(chuàng)建了不同的handler,所以會重復(fù),可以使用暴力方法解決
暴力方式就是每次創(chuàng)建新的對象就清空logger.handlers
我常用的封裝如下
import logging
import time,os
'''
使用方法:
import mylog
log = mylog.Log().getlog()
log.debug("###")
'''
class Log():
def __init__(self,logger="mylog"):
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
self.log_time = "\\"+time.strftime("%Y-%m-%d_%H_%M", time.localtime())+".log"
# 在進(jìn)程路徑創(chuàng)建log文件夾
# self.log_path = os.path.join(os.getcwd() + "\\log")
# 固定在mylog上一級創(chuàng)建
self.log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)) + "\\log")
if os.path.exists(self.log_path) and os.path.isdir(self.log_path):
pass
else:
os.makedirs(self.log_path)
self.log_name = os.path.join(self.log_path + self.log_time)
#因為多出調(diào)用logger會生成多個handlers,所以每次調(diào)用清空handler
self.logger.handlers = []
fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')
formatter = logging.Formatter('[%(levelname)s][%(asctime)s] [%(filename)s]->[%(funcName)s] line:%(lineno)d ---> %(message)s')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
self.logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
fh.close()
def getlog(self):
return self.logger
if __name__ == "__main__":
log = Log().getlog()
log.debug("hello")
以上這篇python將logging模塊封裝成單獨模塊并實現(xiàn)動態(tài)切換Level方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python 日志模塊logging的使用場景及示例
- Python的logging模塊基本用法
- python logging模塊的使用詳解
- python logging模塊的使用
- Python logging模塊handlers用法詳解
- Python logging模塊原理解析及應(yīng)用
- Python logging模塊進(jìn)行封裝實現(xiàn)原理解析
- Python logging日志模塊 配置文件方式
- Python logging模塊異步線程寫日志實現(xiàn)過程解析
- Python logging模塊寫入中文出現(xiàn)亂碼
- Python日志處理模塊logging用法解析
- python 日志 logging模塊詳細(xì)解析
- 多個python文件調(diào)用logging模塊報錯誤
- Python基礎(chǔ)之logging模塊知識總結(jié)
相關(guān)文章
python腳本實現(xiàn)mp4中的音頻提取并保存在原目錄
這篇文章主要介紹了python腳本實現(xiàn)mp4中的音頻提取并保存在原目錄,本文給大家通過實例代碼介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
python實現(xiàn)監(jiān)控windows服務(wù)并自動啟動服務(wù)示例
這篇文章主要介紹了python實現(xiàn)監(jiān)控windows服務(wù)并自動啟動服務(wù)示例,需要的朋友可以參考下2014-04-04
利用Python腳本生成sitemap.xml的實現(xiàn)方法
最近項目中需要用腳本生成sitemap,中間學(xué)習(xí)了一下sitemap的格式和lxml庫的用法。把結(jié)果記錄一下,方便以后需要直接拿來用。下面這篇文章主要介紹了利用Python腳本生成sitemap.xml的實現(xiàn)方法,需要的朋友可以參考借鑒,一起來看看吧。2017-01-01
python+pytest自動化測試函數(shù)測試類測試方法的封裝
這篇文章主要介紹了python+pytest自動化測試函數(shù)測試類測試方法的封裝,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06
python游戲開發(fā)之視頻轉(zhuǎn)彩色字符動畫
這篇文章主要為大家詳細(xì)介紹了python游戲開發(fā)之視頻轉(zhuǎn)彩色字符動畫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04

