簡體   English   中英

如何獲取 logging.LogRecord object 的格式化字符串

[英]How do I get the formatted string of logging.LogRecord object

我只想將一些 INFO 日志消息打印到控制台和日志文件。 我用 StreamHandler 和 FileHandler 創建了一個記錄器。 我將所有消息打印到文件,而控制台中只有 ERROR 和 CRITICAL。 下面是我的日志配置。

# create logger
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)

# Prints only ERROR CRITICAL to stdout
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)

# Prints ALL log levels to file
fh = logging.FileHandler(self.logFile, 'w')
fh.setLevel(logging.DEBUG)

# create formatter
self.formatLogMessage = '[[%(asctime)s]\t[%(levelname)s]\t[%(filename)s]\t[%(funcName)s]\t[%(processName)s]]\t%(message)s'
formatter = logging.Formatter(self.formatLogMessage)

# add formatter
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# add ch to logger
self.logger.addHandler(fh)
self.logger.addHandler(ch)

現在 logger.info() 只打印到文件。

假設我想強制打印一些信息到控制台。 我編寫了一個方法 - printInfoConsole 顯式打印到控制台以及日志為:

# Method to print Info to both log and console
def __printInfoConsole(self, msg, fnName="validate"):
  name = os.path.basename(__file__)
  record = self.logger.makeRecord(self.logger.name,logging.INFO,name,None,msg=msg,args=None,exc_info=None,func=fnName)
  self.logger.handle(record)
  print(record)

這將打印到日志文件和控制台。 但是,當我執行 'print(record') 時,格式不正確:

<LogRecord: __main__, 20, compare_fusionapps.py, None, "bi_cluster: 'fusion.FADomain.bi_cluster.default.minmaxmemory.main' is not set on target.">

與日志文件中的比較為:

[[2019:04:11 15:34:11,474       [INFO]  [compare_fusionapp.py]  [validate]]     bi_cluster: 'fusion.FADomain.bi_cluster.default.minmaxmemory.main' is not set on target.

我嘗試了record.getMessage(),但它只給出了消息,減去了格式。 如何確保我的控制台日志 output 與日志文件匹配。

您需要將格式化程序應用於LogRecord。

print(formatter.format(record))

class logging.Formatter的定義

class logging.Formatter(fmt=None, datefmt=None, style='%' , validate=True, *, defaults=None)

您可以將“樣式”設置為“{”。

暫無
暫無

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

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