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

Question:

I want to print only some INFO log messages to both console and log file. I have created a logger with StreamHandler and FileHandler. I print all messages to File, versus only ERROR and CRITICAL in console. Below is my log configuration.

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

Now logger.info() prints only to file.

Suppose I want to force print some info messages to console. I have written a method – printInfoConsole to print explicitly to console along with log as:

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

This prints to log file and console. However, the formatting is incorrect when I do ‘print(record’) as:

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

Versus in log file as:

[[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.

I tried record.getMessage(), but that gives only the message, minus the formatting.
How do I make sure that my console log output matches the log file.

Asked By: arvindkgs

||

Answers:

You need to apply a Formatter to the LogRecord.

print(formatter.format(record))
Answered By: Dan D.

Definition of class logging.Formatter

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

You can just set the ‘style’ as ‘{‘.

Answered By: SquareSon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.