【问题标题】:Python logging - display the name of the script that triggers the custom logging modulePython 日志记录 - 显示触发自定义日志记录模块的脚本名称
【发布时间】:2022-01-11 14:29:16
【问题描述】:

我想获取触发自定义日志记录模块的脚本名称。 名为module_x 的日志记录模块的格式化程序保存在logger.py 中,如下所示:

import logging.config
import sys

class ConsoleFormatter(logging.Formatter):

    def __init__(self, datefmt, output_format):
        super().__init__()
        self.datefmt = datefmt
        self.output_format = output_format

        """Logging Formatter to add colors and count warning / errors"""
        INFO = '\033[94m'
        DEBUG = '\033[37m'
        WARNING = '\033[33m'
        FAIL = '\033[91m'
        ENDC = '\033[0m'
        BOLD = '\033[1m'
        formatting = output_format

        self.FORMATS = {
            logging.DEBUG: DEBUG + formatting + BOLD + ENDC,
            logging.INFO: INFO + formatting + BOLD +ENDC,
            logging.WARNING: WARNING + formatting + BOLD + ENDC,
            logging.ERROR: FAIL + formatting + BOLD + ENDC,
            logging.CRITICAL: FAIL + formatting + BOLD + ENDC
        }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt, datefmt=self.datefmt)
        return formatter.format(record)


class Log(ConsoleFormatter):

    def __init__(self, datefmt=None, format=None, handlers=None):

        if datefmt == None:
            datefmt = "%Y-%m-%d %H:%M:%S"
        if format == None:
            format = "%(asctime)s [%(levelname)s] [%(filename)s] %(message)s"

        super().__init__(datefmt, format)
        self.logger = logging.getLogger('test')

...

test.py 我正在使用以下方式触发模块:

logs = Log()
logs.output(msg="This is the first test.", level="INFO")

通过这段代码,我得到的显示是:

2022-01-11 16:15:28 [INFO] [logger.py] This is the first test.

我想获取触发logger.py 的文件的名称,即test.py,而不是logger.py。我怎样才能做到这一点?

【问题讨论】:

  • 你能展示你output类的output函数吗?

标签: python logging


【解决方案1】:

您可以在调用getLogger 时使用name a logger,然后您可以在您的记录器格式中将其用作%(name)s

所以在test.py 中你可以使用当前文件名调用:

import os

logs = Log(name=os.path.basename(__file__))
logs.output(msg="This is the first test.", level="INFO")

并将 logger.py 中 Log 类的定义更改为如下内容:

class Log(ConsoleFormatter):

    def __init__(self, name="test", datefmt=None, format=None, handlers=None):  ##

        if datefmt == None:
            datefmt = "%Y-%m-%d %H:%M:%S"
        if format == None:
            format = "%(asctime)s [%(levelname)s] [%(name)s] %(message)s"  ##

        super().__init__(datefmt, format)
        self.logger = logging.getLogger(name)  ##

(用##标记的更改行)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 2013-03-30
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2020-11-07
    相关资源
    最近更新 更多