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]
答案 0 :(得分:0)
正如工作人员在他的评论中所提到的那样,您正在将两个流处理程序附加到“主”记录器。首先在__init__.py
中,然后在__main__.py
中。这也解释了为什么您在__init__.py
内进行的日志记录工作正常,因为__main__.py
尚未附加第二个处理程序。
我怀疑您没有想到此行为的原因是因为您期望记录器与众不同。但是您在__init__.py
和variables.py
中定义的记录器实际上是相同的。当您使用logging.getLogger(logger_name)
使用具有相同logger_name的记录器时,它将返回相同的记录器。因此,当您在logging.getLogger('Main')
中调用variables.py
时,从在__init__.py
中添加它以来,它仍然具有StreamHandler。
根据您想要的行为,您应该给它们指定不同的名称,或者删除第二个addHandler。
应注意,记录器名称遵循层次结构。 my_package
的日志配置还将配置任何my_package.model
,my_package.views
等的日志记录。根记录器只是带有空字符串(logging.getLogger("")
)的记录器。 / p>
有关更多详细信息,我建议您只进行the official docs。