我使用了日誌模塊,發現了一些對我來說不太清楚的事情。使用json配置文件進行Python日誌記錄
首先,因爲它是一個大程序,我希望代碼儘可能簡單,因此使用json配置文件。
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
},
"extra": {"format":"%(asctime)-16s %(name)-8s %(filename)-12s %(lineno)-6s %(funcName)-30s %(levelname)-8s %(message)s",
"datefmt":"%m-%d %H:%M:%S"}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"info_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "INFO",
"formatter": "simple",
"filename": "info.log",
"maxBytes": 10485760,
"backupCount": 40,
"encoding": "utf8"
},
"error_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "ERROR",
"formatter": "simple",
"filename": "errors.log",
"maxBytes": 10485760,
"backupCount": 40,
"encoding": "utf8"
}
},
"loggers": {
"my_module": {
"level": "ERROR",
"handlers": ["console"],
"propagate": "no"
}
},
"root": {
"level": "INFO",
"handlers": ["console", "info_file_handler", "error_file_handler"]
}
}
此JSON文件被導入並使用。它似乎工作正常。 不幸的是有一些問題。 完成代碼(仍在工作)後,記錄器不會關閉文件。由於這一點,他將在下一次運行中將新的運行追加到舊的日誌文件中。沒有可能刪除它或truncate()沒有問題。 因此我想刪除處理程序寫入文件。不幸的是,它看起來像logger.handlers是空的,因此我無法在任何地方找到它們。大概有一個想法?
此外,日誌文件還有一個主要問題。記錄器只是追加所有新東西而不開始新行。結果是無盡的單行日誌。
主測試程序:
import sys
import os
import json
import logging.config
import my_module
def setup_logging(
default_path='logging.json',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
def main():
setup_logging()
logger = logging.getLogger(__name__)
logger.info('Startlogging:')
my_module.foo()
b = my_module.Bar()
b.bar()
print logger.handlers
if __name__ == '__main__':
main()
你可以顯示實際日誌記錄的代碼嗎?你也看過這裏嗎? https://docs.python.org/3/library/logging.html – sietse85
'進口記錄
高清富():
記錄= logging.getLogger(__ name__)
logger.info('嗨,FOO - 信息 ')
logger.debug(' 嗨,富 - 調試 ')
logger.error(' 嗨,富 - 錯誤「)
Bar類(對象):
高清__init __(自我,記錄器=無):
self.logger = logger或logging.getLogger(__ name__)
def bar(self):
('嗨,酒吧 - 信息')
self.logger.debug('嗨,酒吧 - 調試')
self.logger.error('嗨,酒吧 - 錯誤')
' – RandomMario
所以你現在已經得到了整個代碼。認爲最大的問題是最後不要關閉處理程序。 BUt作爲logger.handlers返回[]我不知道如何手動關閉它們 – RandomMario