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



我只想将一些 INFO 日志消息打印到控制台和日志文件中。我用StreamHandler和FileHandler创建了一个记录器。我将所有消息打印到文件,而不是控制台中的错误和严重。下面是我的日志配置。

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

这将打印到日志文件和控制台。但是,当我将"打印(记录"(为时,格式不正确:

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

您需要将

格式化程序应用于日志记录。

print(formatter.format(record))

类日志记录的定义。格式化程序

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

您可以将">样式"设置为">{"。

最新更新