1. 程式人生 > >python 解決logging模組重複輸出日誌

python 解決logging模組重複輸出日誌

場景:多個py檔案呼叫Logging,從主檔案匯入另外的py檔案時日誌會反覆輸出幾條

原因參考:

https://blog.csdn.net/huilan_same/article/details/51858817

解決:將logger例項放到單獨的py檔案,其他檔案都import該py

my_log.py

#! /usr/bin/python
# encoding:utf-8

# 配置檔案
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read('config/db_monitor.conf')
# 日誌
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logfile = conf.get("log","check_logfile")
fh = logging.FileHandler(logfile,mode='a')
fh.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)

呼叫:

import my_log as my_log
my_log.logger.info('%s:初始化os_info表' % tags)