如何获取日志记录对象logging.LogRecord的格式化字符串

3

我希望只将一些 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.">

Versus在日志文件中的表示:

[[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(),但这只给出消息,不包括格式化。如何确保我的控制台日志输出与日志文件匹配。

2个回答

5

您需要对LogRecord应用格式化程序。

print(formatter.format(record))

1

类 logging.Formatter 的定义

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

你可以将'style'设置为'{'。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接