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

时间:2019-04-11 10:34:08

标签: python python-2.7 logging

我只想将一些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)

这将打印到日志文件和控制台。但是,当我将'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(),但是只给出消息,减去格式。 如何确保我的控制台日志输出与日志文件匹配。

1 个答案:

答案 0 :(得分:1)

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

print(formatter.format(record))
相关问题