簡體   English   中英

Python“記錄器”模塊兩次記錄

[英]Python 'Logger' module double-logging

解決了:

重命名我的兩個記錄器已解決了此問題。 出現我的問題是因為我將再次在主文件中執行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)

我不確定是什么導致了這個問題...我認為這是在初始化文件中定義了一個記錄器,然后在變量文件中定義了一個記錄器。

如果有幫助,我將在下面提供我的文件結構的副本:

 <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]

正如工作人員在他的評論中提到的那樣,您正在將兩個流處理程序附加到“主”記錄器。 首先在__init__.py ,然后在__main__.py 這也解釋了為什么您在__init__.py的日志記錄正常工作,因為__main__.py尚未附加第二個處理程序。

我懷疑您沒有期望這種行為的原因是因為您期望記錄器與眾不同。 但是您在__init__.pyvariables.py中定義的記錄器實際上是相同的。 當使用logging.getLogger(logger_name)和相同的logger_name檢索記錄器時,它將返回相同的記錄器。 因此,當您在variables.py調用logging.getLogger('Main')時,從在__init__.py中添加它以來,它仍然具有StreamHandler。

根據您想要的行為,您應該給它們指定不同的名稱,或者刪除第二個addHandler。

應當注意,記錄器名稱遵循層次結構。 my_package日志配置還將配置任何my_package.modelmy_package.views等的日志。根記錄器只是帶有空字符串( logging.getLogger("") )的記錄器。

有關更多詳細信息,我建議您只閱讀官方文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM