简体   繁体   English

将logger作为参数传递给函数,并在日志文件中获取函数名称

[英]Passing logger as an argument to functions and get the function name in log file

I am using logging package to create a log file for my application. 我正在使用日志记录包为我的应用程序创建日志文件。 In the main function, I created the logger, handler, and formatter and set the logging level as below: 主要功能中,我创建了记录器,处理程序和格式化程序,并将记录级别设置如下:

try:
    os.remove('xxx.log')
except WindowsError:
    pass
LOG_FILENAME = 'xxx.log'
logger = logging.getLogger(__name__)
logger.setLevel(20)
ch = logging.FileHandler(LOG_FILENAME)
ch.setLevel(20)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

logger.info("info message")

then, I call different functions that I want to have the logger as well. 然后,我调用了我也想拥有记录器的不同功能。 So I pass logger as an argument to that function and then use the logger.info to have the info log in that function. 因此,我将logger作为该函数的参数传递,然后使用logger.info将信息记录在该函数中。 The problem is that I need the name of the function to be listed in the log file so I coded as below: 问题是我需要在日志文件中列出该函数的名称,因此我将其编码如下:

test(a, b, c, d, e, f, g, logger)
def test test(a, b, c, d, e, f, g, logger):
    logger = logging.getLogger(__name__)
    logger.info("test ....")

What is wrong here? 怎么了 How can fix the issue? 如何解决该问题? Any suggestion to improve my coding is also appreciated. 任何建议,以改善我的编码,也表示赞赏。

The formatter needs to be changed to below: 格式化程序需要更改为以下内容:

logging.Formatter("%(asctime)s - %(module)s - %(levelname)s - %(message)s")

So instead %(name)s, the %(module)s needs to be implemented based on the documentation. 因此,需要根据文档来实现%(name),而需要实现%(module)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM