Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get formatter string from a logging.formatter object in Python?

Tags:

python

logging

Hi I want to make a logging manager gui. Basically I want to get the tree structure of loggers and show their level and formatter in a pyqt gui. How can I get the format string from a formatter associated a handler object?

eg:

import logging
_logger = logging.getLogger('myLogger')

ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)s:%(levelname)s: %(message)s')
ch.setFormatter(formatter)
_logger.addHandler(ch)
_logger.propagate=0

Now I have the _logger, how can I get string '%(name)s:%(levelname)s: %(message)s' from the logging.Formatter object?

>>> _logger.handlers[0]
<logging.StreamHandler object at 0x13807610>
>>> _logger.handlers[0].formatter
<logging.Formatter object at 0x13807690>
like image 407
Shuman Avatar asked Jul 16 '16 17:07

Shuman


People also ask

How do you show logging information in Python?

Python Logging – INFO Level To log an INFO line using Python Logging, Check if the logger has atleast a logging level of INFO. Use logging.info() method, with the message passed as argument, to print the INFO line to the console or log file.

What is Qualname in python logging?

The qualname entry is the hierarchical channel name of the logger, that is to say the name used by the application to get the logger.

What is logging getLogger (__ Name __)?

getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.

What is StreamHandler Python?

StreamHandler. The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).


1 Answers

logging.Formatter instances have a _fmt attribute:

>>> _logger.handlers[0].formatter
<logging.Formatter object at 0x102c72fd0>
>>> _logger.handlers[0].formatter._fmt
'%(name)s:%(levelname)s: %(message)s'

You can always use dir() and vars() on objects to see what names might be available:

>>> vars(_logger.handlers[0].formatter)
{'datefmt': None, '_fmt': '%(name)s:%(levelname)s: %(message)s'}

or you could just look at the source code (linked from the top of the module documentation).

like image 159
Martijn Pieters Avatar answered Nov 01 '22 23:11

Martijn Pieters