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

arv*_*kgs 3 python logging python-2.7

我只想将一些 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)
Run Code Online (Sandbox Code Playgroud)

现在 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)
Run Code Online (Sandbox Code Playgroud)

这会打印到日志文件和控制台。但是,当我执行“打印(记录”)时,格式不正确:

<LogRecord: __main__, 20, compare_fusionapps.py, None, "bi_cluster: 'fusion.FADomain.bi_cluster.default.minmaxmemory.main' is not set on target.">
Run Code Online (Sandbox Code Playgroud)

与日志文件中的对比如下:

[[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.
Run Code Online (Sandbox Code Playgroud)

我尝试了 record.getMessage(),但这只给出了消息,减去了格式。如何确保我的控制台日志输出与日志文件匹配。

Dan*_* D. 6

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

print(formatter.format(record))
Run Code Online (Sandbox Code Playgroud)