问题在Python中设置自定义记录器



所以我目前正在重新设计我们基于python的自动测试系统(ATS),我遇到了一个真正令人头痛的日志记录问题。我花了几个小时看了youtube上的教程和文章,但我还没有找到一个明确的答案。

我想用一个日志记录器替换所有的打印语句,该日志记录器将输出到控制台和.txt文件。我已经创建了Test Log.txt(文件名中有datetime),但是该文件是空白的,打印的文本也没有出现在控制台中。这是使用logger.debug。这就像在文本传递给.txt文件之前创建了。

我本来是通过PrintLog.debug调用的,但这导致visual studio告诉我PrintLog.py没有名为debug的属性。我真的希望我可以只是一点代码,可以由各种脚本调用,而不是把它烤到每个单独的脚本。此外,如果你能帮我在'OutputLogs'子文件夹中生成日志,我将不胜感激。

import os
import time
import datetime
def timeStamped(fname, fmt='%Y-%m-%d_%H.%M - {fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
#Records Current date & time and appends it to the file namme of the txt log created at the end of this script.
import logging

def PrintLog(self):
PrintLog = logging.getLogger(__name__)
PrintLog.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s:%(asctime)s')
file_handler = logging.FileHandler(timeStamped('Test Report.txt'))
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(formatter)
PrintLog.addHandler(file_handler)
PrintLog.addHandler(stream_handler)
编辑:所以要澄清,这是记录器,但我想调用它,并从另一个Python脚本传递信息给它。
import os
import time
import sys
import subprocess
import datetime
import logging
from PrintLog import PrintLog

def timeStamped(fname, fmt='%Y-%m-%d_%H.%M.%S - {fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
#Records Current date & time and appends it to the file namme of the txt log created at the end of this script.

from sys import platform
if platform == "darwin":
PrintLog('Operating System = MAC')    
elif platform == "win32":
PrintLog('Operating System = Windows')

操作系统语句等信息不会传递给PrintLog脚本。

logging.getLogger(__name__)创建一个新的记录器,与您在自己的日志模块中创建的logger变量不同,因为__name__在每个模块中都是不同的。

从您自己的模块导入logger并使用它,或者配置根日志记录器:

logger = logging.getLogger()  # Without arguments, it gets the root logger.
logger.setLevel(logging.DEBUG)
# ... add handlers etc. ...

最新更新