簡體   English   中英

將logger作為參數傳遞給函數,並在日志文件中獲取函數名稱

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

我正在使用日志記錄包為我的應用程序創建日志文件。 主要功能中,我創建了記錄器,處理程序和格式化程序,並將記錄級別設置如下:

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")

然后,我調用了我也想擁有記錄器的不同功能。 因此,我將logger作為該函數的參數傳遞,然后使用logger.info將信息記錄在該函數中。 問題是我需要在日志文件中列出該函數的名稱,因此我將其編碼如下:

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 ....")

怎么了 如何解決該問題? 任何建議,以改善我的編碼,也表示贊賞。

格式化程序需要更改為以下內容:

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

因此,需要根據文檔來實現%(name),而需要實現%(module)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM