调用其他模块时显示原始模块的名称

2024-09-30 14:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建集中式日志记录。这基本上与下面的脚本类似

logit模块将根据调用它的脚本名称创建一个文件。在这种情况下,apiCaller

最初,我在调用logit时手动定义了它,但是我正在搜索away for logit以确定日志本身的来源

这里有3个模块:

main.py:

def runAnalytic(script):
    importlib.import_module("monitoringScripts."+script["package"]+"."+script["module"], package=None)

packageModule = [{"package":"awesome","module":"apiCaller"}]

with concurrent.futures.ThreadPoolExecutor() as executor:
    results = executor.map(runAnalytic, packageModule)

apiCaller.py(上面的模块)

from adminTools.logger import logit
logit.create(results[i]["items"][r]["userId"],"apiCaller") #How i currently pass the script name, i want to get rid of this.

logit.py处理所有其他脚本所需的所有日志(集中式日志)

import sys, logging, logging.handlers, pathlib
#Path for all log files for scriptHub
logdir = str(pathlib.Path(__file__).parent.absolute())

#Creates the log file based on a given name from the script
def create(logMessage,scriptName, level="DEBUG"):
    #create filename
    log_filename = logdir+"/sysLogs/"+scriptName+".logs"
    #Creates the logging object
    my_logger = logging.getLogger(scriptName)
    my_logger.setLevel(logging.DEBUG)
    #Formats the log:
    formatter = logging.Formatter('%(asctime)s - %(message)s - %(name)s')
    #Gives the log file a limit for 100mb if it goes bigger than this, it will create another file, but keep the old one
    handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=100000000, backupCount=1)
    handler.setFormatter(formatter)
    #Handlers need to be cleared to stop duplicated logs.
    if (my_logger.hasHandlers()):
        my_logger.handlers.clear()
    my_logger.addHandler(handler)
    #creates the log message
    my_logger.debug(logMessage)

所以,我不确定这对你们是有帮助还是有阻碍,哈哈

本质上,我希望logit从调用它的模块中获取脚本名,而不是向logit提供脚本名。例如,在本例中,“apiCaller”将是传递给logit的名称


Tags: 模块thepyimport脚本logformy
2条回答

好的,有一个重写的问题:

我看到它是以另一种方式完成的,而不是您这样做的——获取一个记录器,然后设置它(模块中有两行,而不是一行)。记录器是每个模块的东西,并且始终存在

在您的情况下,每次都重新获取记录器并重新生成处理程序

这样你就不能利用logging模块提供的美丽的可能性


因此,基本上,另一种方法是:

在每个脚本中执行logger = logging.getLogger(__name__),通常位于导入下方的顶部附近

+您只需调用logit.setupLogger(logger)。(在您的情况下,在下一行中。在脚本的情况下,我将它保留在main函数中-这样,如果我将脚本作为模块导入,我将调用imported_module.logger上需要的任何日志设置,以便它不会垃圾邮件发送错误的日志文件。:D)

重写logit.py

import sys, logging, logging.handlers, pathlib
#Path for all log files for scriptHub
logdir = str(pathlib.Path(__file__).parent.absolute())

#Creates the log file based on a given name from the script
def create(my_logger, level=logging.DEBUG):
    #create filename
    log_filename = logdir+"/sysLogs/"+logger.name+".logs"

    my_logger.setLevel(level)
    #Formats the log:
    formatter = logging.Formatter('%(asctime)s - %(message)s - %(name)s')
    #Gives the log file a limit for 100mb if it goes bigger than this, it will create another file, but keep the old one
    handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=100000000, backupCount=1)
    handler.setFormatter(formatter)
    #Handlers need to be cleared to stop duplicated logs.
    if (my_logger.hasHandlers()):
        my_logger.handlers.clear()
    my_logger.addHandler(handler)

这样,您只需在logit中设置记录器的内部(包括文件处理程序),并且可以使用标准的logging东西:

  • 您可以在模块中使用任何级别的日志记录:
logger.info("like")
logger.warning("this")
  • 您可以像上面那样在代码中编写每个日志消息-使代码充满日志消息请记住,调试消息应该包含调试所需的所有信息,这有时包括大量信息+请记住,调试消息可能存在于信息消息旁边,只是具有不同的详细信息(例如,“从X获取信息”是信息,“发送请求“some/address/here”和接收的“chunk of data here”是调试)
  • 当您需要降低级别时-例如,您调试了消息,厌倦了看到这么多的.much.info(或者只是从开发到生产)-您只需将logit.setupLogger(logger)更改为logit.setupLogger(logger, logging.INFO)或任何您需要的级别

按照您的方式记录日志似乎是一个好主意,但是logging模块在您学习如何使用它时非常强大Here's a How-To from Python's docs,但是它有很多信息,所以simpler tutorials on python logging是一个更好的开始

Tbh我也从我自己的日志记录实践开始,甚至在阅读了文档和教程之后,因为我根本不懂。当我在使用的库中看到它时,我才切换到上面的方法。:)

这个问题不是很清楚,但是你可以使用inspect.stack()

loggy.py

import inspect

def log(s):
    caller = inspect.stack()[1]
    print(f"{caller.filename} line {caller.lineno} says: {s}")

thing.py

import loggy

loggy.log("Hey!")

/v/f/n/8/T/tmp.ZiRzgsqi $ python3 thing.py
thing.py line 3 says: Hey!
/v/f/n/8/T/tmp.ZiRzgsqi $

相关问题 更多 >