【问题标题】:How to get script/file name of particular line of code?如何获取特定代码行的脚本/文件名?
【发布时间】:2019-11-02 13:40:40
【问题描述】:

我有一个通用文件 log.py,我在其中导入了 python 日志记录并使用了其中的所有函数。

现在我需要这样格式化日志

(current_script_name) [levelname] message

log.py

import logging
import inspect
import sys

class log(object):
    #file_name = sys.argv[0] #this will give b.py instead of a.py
    file_name = str(inspect.getfile(inspect.currentframe())).split("/")[-1]
    logging.basicConfig(level=logging.INFO, format="("+file_name+") [%(levelname)s] %(message)s")
    def __init__(self):
        pass
    def info(msg):
        logging.info(msg)
    def error(msg):
        logging.error(msg)
    def warning(msg):
        logging.warning(msg)
    def debug(msg):
        logging.debug(msg)

现在,我有另一个名为 a.py 的文件 我在哪里导入了上面的文件并使用了

import log
def some():
    log.info("Hello this is information")

当我在b.py 中调用some() 时,这将在下面给出输出

(log.py) [INFO] Hello this is information

但我希望低于输出,因为在 a.py 中使用了 log.info() 代码

(a.py) [INFO] Hello this is information

注意:我不应该在a.py 中为log.info(msg) 行传递任何参数

【问题讨论】:

    标签: python-3.x python-2.7


    【解决方案1】:

    一种解决方案是将执行脚本的文件名传递给记录器。

    a.py 内部:

    log.info("Hello this is information", executing_script=__file__)
    

    (有关使用文件变量的更多信息:https://note.nkmk.me/en/python-script-file-path/

    如果您这样做,您将不得不更新日志类中的所有函数定义。或者,您可以在日志类初始化程序中包含执行脚本文件名:

    class log(object):
      def __init__(self, executing_script):
        self.file_name = executing_script
      # ...
    

    这样您就可以在日志记录函数中引用self.file_name,而不必向每个函数传递一个值。

    【讨论】:

    猜你喜欢
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2012-11-29
    • 1970-01-01
    • 2017-04-01
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多