【发布时间】: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函数吗?