您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何解決Python logging模塊無(wú)法正常輸出日志的問(wèn)題,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
先上代碼
File:logger.conf [formatters] keys=default [formatter_default] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s class=logging.Formatter [handlers] keys=console, error_file [handler_console] class=logging.StreamHandler formatter=default args=tuple() [handler_error_file] class=logging.FileHandler level=INFO formatter=default args=("logger.log", "a") [loggers] keys=root [logger_root] level=DEBUG formatter=default handlers=console,error_file
File:logger.py #!/bin/env python import logging from logging.config import logging class Test(object): """docstring for Test""" def __init__(self): logging.config.fileConfig("logger.conf") self.logger = logging.getLogger(__name__) def test_func(self): self.logger.error('test_func function') class Worker(object): """docstring for Worker""" def __init__(self): logging.config.fileConfig("logger.conf") self.logger = logging.getLogger(__name__) data_logger = logging.getLogger('data') handler = logging.FileHandler('./data.log') fmt = logging.Formatter('%(asctime)s|%(message)s') handler.setFormatter(fmt) data_logger.addHandler(handler) data_logger.setLevel(logging.DEBUG) self.data_logger = data_logger def test_logger(self): self.data_logger.error("test_logger function") instance = Test() self.data_logger.error("test_logger output") instance.test_func() def main(): worker = Worker() worker.test_logger() if __name__ == '__main__': main()
問(wèn)題一:測(cè)試過(guò)程中,只能打印出test_logger function一條語(yǔ)句
問(wèn)題二:明明只在data_logger中打印出語(yǔ)句,但是logger的日志中也出現(xiàn)了相關(guān)的日志。
問(wèn)題一解決方案:
利用python -m pdb logger.py 語(yǔ)句對(duì)腳本進(jìn)行調(diào)試發(fā)現(xiàn),在執(zhí)行instance = Test()語(yǔ)句后,通過(guò)print '\n'.join(['%s:%s' % item for item in self.data_logger.__dict__.items()])調(diào)試語(yǔ)句看到data_logger的disable屬性值由0變成了True,此時(shí)logger的對(duì)應(yīng)屬性也發(fā)生了相同的變化。這種變化導(dǎo)致了logger對(duì)象停止記錄日志。
參考python logging模塊的相關(guān)手冊(cè)發(fā)現(xiàn)
“The fileConfig() function takes a default parameter, disable_existing_loggers, which defaults to True for reasons of backward compatibility. This may or may not be what you want, since it will cause any loggers existing before the fileConfig() call to be disabled unless they (or an ancestor) are explicitly named in the configuration.”
的說(shuō)明,即調(diào)用fileconfig()函數(shù)會(huì)將之前存在的所有l(wèi)ogger禁用。
在python 2.7版本該fileConfig()函數(shù)添加了一個(gè)參數(shù),logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True),可以顯式的將disable_existing_loggers設(shè)置為FALSE來(lái)避免將原有的logger禁用。
將上述代碼中的Test類中的logging.config.fileConfig函數(shù)改成logging.config.fileConfig("./logger.conf", disable_existing_loggers=0)就可以解決問(wèn)題。
不過(guò)該代碼中由于位于同一程序內(nèi),可以直接用logging.getLogger(LOGGOR_NAME)函數(shù)引用同一個(gè)logger,不用再調(diào)用logging.config.fileConfig函數(shù)重新加載一遍了。
問(wèn)題二解決方案:
logger對(duì)象有個(gè)屬性propagate,如果這個(gè)屬性為True,就會(huì)將要輸出的信息推送給該logger的所有上級(jí)logger,這些上級(jí)logger所對(duì)應(yīng)的handlers就會(huì)把接收到的信息打印到關(guān)聯(lián)的日志中。logger.conf配置文件中配置了相關(guān)的root logger的屬性,這個(gè)root logger就是默認(rèn)的logger日志。
修改后的如下:
File:logger.conf [formatters] keys=default, data [formatter_default] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s class=logging.Formatter [formatter_data] format=%(asctime)s|%(message)s class=logging.Formatter [handlers] keys=console, error_file, data_file [handler_console] class=logging.StreamHandler formatter=default args=tuple() [handler_error_file] class=logging.FileHandler level=INFO formatter=default args=("logger.log", "a") [handler_data_file] class=logging.FileHandler level=INFO formatter=data args=("data_new.log", "a") [loggers] keys=root, data [logger_root] level=DEBUG handlers=console,error_file [logger_data] level=DEBUG handlers=data_file qualname=data propagate=0
File:logger.py #!/bin/env python import logging from logging.config import logging class Test(object): """docstring for Test""" def __init__(self): self.logger = logging.getLogger(__name__) def test_func(self): self.logger.error('test_func function') class Worker(object): """docstring for Worker""" def __init__(self): logging.config.fileConfig("logger.conf") self.logger = logging.getLogger(__name__) self.data_logger = logging.getLogger('data') def test_logger(self): self.data_logger.error("test_logger function") instance = Test() self.data_logger.error("test_logger output") instance.test_func() def main(): worker = Worker() worker.test_logger() if __name__ == '__main__': main()
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何解決Python logging模塊無(wú)法正常輸出日志的問(wèn)題”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。