python两次调用write_使用Python日志记录两次出现日志消息

I'm using Python logging, and for some reason, all of my messages are appearing twice.

I have a module to configure logging:

# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.

def configure_logging(self, logging_file):

self.logger = logging.getLogger("my_logger")

self.logger.setLevel(logging.DEBUG)

self.logger.propagate = 0

# Format for our loglines

formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# Setup console logging

ch = logging.StreamHandler()

ch.setLevel(logging.DEBUG)

ch.setFormatter(formatter)

self.logger.addHandler(ch)

# Setup file logging as well

fh = logging.FileHandler(LOG_FILENAME)

fh.setLevel(logging.DEBUG)

fh.setFormatter(formatter)

self.logger.addHandler(fh)

Later on, I call this method to configure logging:

if __name__ == '__main__':

tom = Boy()

tom.configure_logging(LOG_FILENAME)

tom.buy_ham()

And then within say, the buy_ham module, I'd call:

self.logger.info('Successfully able to write to %s' % path)

And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening...lol. Assuming I've missed something obvious.

Cheers,

Victor

解决方案

You are calling configure_logging twice (maybe in the __init__ method of Boy) : getLogger will return the same object, but addHandler does not check if a similar handler has already been added to the logger.

Try tracing calls to that method and eliminating one of these. Or set up a flag logging_initialized initialized to False in the __init__ method of Boy and change configure_logging to do nothing if logging_initialized is True, and to set it to True after you've initialized the logger.

If your program creates several Boy instances, you'll have to change the way you do things with a global configure_logging function adding the handlers, and the Boy.configure_logging method only initializing the self.logger attribute.

Another way of solving this is by checking the handlers attribute of your logger:

logger = logging.getLogger('my_logger')

if not logger.handlers:

# create the handlers and call logger.addHandler(logging_handler)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值