【问题标题】:Python 'Logger' module double-loggingPython 'Logger' 模块双重记录
【发布时间】:2019-05-03 17:13:45
【问题描述】:

已解决:

通过重命名我的两个记录器解决了这个问题。我的问题出现了,因为我会在主文件中再次执行log.getLogger。这导致制作了 2 个记录器实例。解决方案是删除第二个调用,或重命名两者之一。

我正在尝试为我当前的项目设置一个自定义记录器,但我很难让它在 __init__.py 文件之外正常工作。问题是我记录的任何内容都会被记录两次。

我的代码:

__Init__.py:

import datetime as date
import os
import platform as plt
import logging as log


prefsDirectory = 'prefs/'
prefsName = 'preferences.txt'
prefsLocation = prefsDirectory + prefsName
now = date.datetime.now()

# SETUP

if not(os.path.exists(prefsLocation)):
    if not(plt.system() == "Darwin"):
        os.mknod(prefsLocation)
        with(open(prefsLocation, 'w+')) as f:
            f.write('Log increment:\n' + str(1) + "\n")
            f.close()
            pass
    else:
        if not(os.path.exists(prefsDirectory)):
            os.mkdir(prefsDirectory)
        with(open(prefsLocation, 'w+')) as f:
            f.close()
            pass
        with(open(prefsLocation, 'w+')) as f:
            f.write('Log increment:\n' + str(0) + "\n")
            f.write('\nCurrent Date:\n' + str(now.day) + "\n")
            f.close()
            pass

with(open(prefsLocation, "r")) as f:
    data = f.readlines()

if not(str(now.day) == data[4]):
    data[4] = str(now.day)
    data[1] = str(0) + '\n'
    # print('This ran')
else:
    inc = str(int(data[1]) + 1)
    data[1] = inc + "\n"


with(open(prefsLocation, "w")) as f:
    lines = (str(item) for item in data)
    for item in lines:
        f.write(item)

dateC = "[" + str(now.year) + "-" + str(now.month) + "-" + data[4] + "]"
logDirectory = "logs/"
inc = int(data[1])
logName2 = str(dateC) + "-" + str(inc)
logName = logName2 + ".log"
logLocation = logDirectory + logName


if not(os.path.exists(logLocation)):
    if not(plt.system() == "Darwin"):
        os.mknod(logLocation)
    else:
        if not(os.path.isdir(logDirectory)):
            os.mkdir(logDirectory)

        with (open(logLocation, 'w+')) as f:
            f.close()
            pass


formatter = log.Formatter("[%(asctime)s][%(levelname)s][%(module)s] : %(message)s \n", "%H:%M-%S" + "s")

handler = log.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel("DEBUG")

logger = log.getLogger("Main")
logger.addHandler(handler)
log.basicConfig(filename=logLocation, level=log.DEBUG, filemode="w",
                format="[%(asctime)s][%(levelname)s][%(module)s] : %(message)s \n", datefmt="%H:%M-%S" + "s")

logger.info("[LOG NUMBER: " + str(inc) + "]")
logger.info("Found Settings file")
logger.info("Generated Log File")

__main__.py:

# IMPORTS

import logging as log
from main import variables as vrs


# VARIABLES

logg = vrs.logg
logg.addHandler(vrs.handlerMain)
log.basicConfig(filename=vrs.logLocation, level=log.DEBUG, filemode="w",
                format="[%(asctime)s][%(levelname)s][%(module)s] : %(message)s \n", datefmt="%H:%M-%S" + "s")

with(open(vrs.prefsLocation, "r")) as f:
    data = f.readlines()

# BODY

logg.info('Program Loading Completed.')

# Make a data holding file.

vrs.makefile('prefs/data.txt', 'prefs/', "Data File")

variables.py:

import datetime as date
import logging as log
import os
import platform as plt


prefsDirectory = 'prefs/'
prefsName = 'preferences.txt'
prefsLocation = prefsDirectory + prefsName


with(open(prefsLocation, "r")) as f:
    data = f.readlines()

now = date.datetime.now()
dateC = "[" + str(now.year) + "-" + str(now.month) + "-" + data[4] + "]"


logDirectory = "logs/"
inc = int(data[1])
logName2 = str(dateC) + "-" + str(inc)
logName = logName2 + ".log"
logLocation = logDirectory + logName


formatter = log.Formatter("[%(asctime)s][%(levelname)s][%(module)s] : %(message)s \n", "%H:%M-%S" + "s")

handler = log.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel("DEBUG")
handler.set_name('Main')

handlerMain = log.StreamHandler()
handlerMain.setFormatter(formatter)
handlerMain.setLevel("DEBUG")

logg = log.getLogger("Main")



def makefile(filelocation, filedirectory, filename):
    if not (os.path.exists(filelocation)):
        if not (plt.system() == "Darwin"):
            os.mknod(filelocation)
            with(open(filelocation, 'w+')) as file:
                file.write('File Created:\n' + dateC + "\n")
                file.close()
                pass
        else:
            if not (os.path.exists(filedirectory)):
                os.mkdir(filedirectory)
            with(open(filelocation, 'w+')) as file:
                file.write('File Created:\n' + dateC + "\n")
                file.close()
                pass

    logg.info('Created file: ' + filename)

我不确定究竟是什么导致了这个问题...我认为这是在 init 文件中定义一个记录器,在变量文件中定义一个第二个。

如果有帮助,我将在下面提供我的文件结构的副本:

<a href="https://gyazo.com/5cb1221a65a9ad50adf2a355f92f90e4"><img src="https://i.gyazo.com/5cb1221a65a9ad50adf2a355f92f90e4.png" alt="Image from Gyazo" width="315"/></a>

<a href="https://gyazo.com/39f1b61ca09ed364080254a0f678db80"><img src="https://i.gyazo.com/39f1b61ca09ed364080254a0f678db80.png" alt="Image from Gyazo" width="1280"/></a>

[ 我似乎无法在帖子中输入 gyazo 图像,你们中的一位社区版主可以帮我输入这些图像吗?另外,查看名为 AoC2018 的文件夹]

【问题讨论】:

  • 看起来您正在添加两个处理程序,这将导致两个输出。你能发布一个小版本的代码吗,很难说到底发生了什么?
  • 请不要在您的问题中编辑答案。相反,请考虑添加您自己的答案。另外,不要标记“已解决”,因为从您接受答案这一事实中就可以看出这一点。

标签: python python-3.x macos pycharm


【解决方案1】:

正如 jobevers 在他的评论中提到的那样,您将两个流处理程序附加到“主要”记录器。首先是__init__.py,然后是__main__.py。这也解释了为什么您在 __init__.py 中的日志记录工作正常,因为 __main__.py 尚未附加第二个处理程序。

我怀疑您没有预料到这种行为的原因是因为您希望记录器是不同的。但是您在__init__.py 和variables.py 中定义的记录器实际上是相同的。当您使用具有相同 logger_name 的 logging.getLogger(logger_name) 检索记录器时,它会返回相同的记录器。因此,当您在 variables.py 中调用 logging.getLogger('Main') 时,它仍然具有从在 __init__.py 中添加时的 StreamHandler。

根据您想要的行为,您应该给它们不同的名称或删除第二个 addHandler。

应该注意,记录器名称遵循层次结构。 my_package 的日志配置还将配置任何 my_package.model、my_package.views 等的日志记录...根记录器只是带有空字符串 (logging.getLogger("")) 的记录器。

有关更多详细信息,我建议您直接通过the official docs。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2020-06-19
  • 1970-01-01
  • 2014-02-01
相关资源
最近更新 更多