使用 Python 日志记录模块时的重复日志输出 [英] Duplicate log output when using Python logging module

查看:64
本文介绍了使用 Python 日志记录模块时的重复日志输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 记录器.以下是我的代码:

I am using python logger. The following is my code:

import os
import time
import datetime
import logging
class Logger :
   def myLogger(self):
      logger = logging.getLogger('ProvisioningPython')
      logger.setLevel(logging.DEBUG)
      now = datetime.datetime.now()
      handler=logging.FileHandler('/root/credentials/Logs/ProvisioningPython'+ now.strftime("%Y-%m-%d") +'.log')
      formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
      handler.setFormatter(formatter)
      logger.addHandler(handler)
      return logger

我遇到的问题是,对于每个 logger.info 调用,我都会在日志文件中获得多个条目.我该如何解决这个问题?

The problem I have is that I get multiple entries in the log file for each logger.info call. How can I solve this?

推荐答案

logging.getLogger() 返回给定名称的相同实例.(文档)

The logging.getLogger() is returns the same instance for a given name. (Documentation)

问题是每次调用 myLogger() 时,它都会向实例添加另一个处理程序,从而导致重复日志.

The problem is that every time you call myLogger(), it's adding another handler to the instance, which causes the duplicate logs.

也许是这样?

import os
import time
import datetime
import logging

loggers = {}

def myLogger(name):
    global loggers
    
    if loggers.get(name):
        return loggers.get(name)
    else:
        logger = logging.getLogger(name)
        logger.setLevel(logging.DEBUG)
        now = datetime.datetime.now()
        handler = logging.FileHandler(
            '/root/credentials/Logs/ProvisioningPython' 
            + now.strftime("%Y-%m-%d") 
            + '.log')
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        loggers[name] = logger
                       
        return logger

这篇关于使用 Python 日志记录模块时的重复日志输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆