I want to count the number of times logger.info
and logger.error
has been hit.
I am planning to override default method error of logging, Can anyone suggest me how to do that ?
Need help to override error method so that every time code hit it count the value and increment counter.
You can firstly implement your own logger class by deriving from logging. Logger, in which you override the methods you target. And then you pass the logger class to the logging system by using logging. setLoggerClass.
Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.
By default, the root log level is WARN, so every log with lower level (for example via logging.info("info") ) will be ignored. Another particularity of the root logger is that its default handler will be created the first time a log with a level greater than WARN is logged.
You can firstly implement your own logger class by deriving from logging.Logger, in which you override the methods you target. And then you pass the logger class to the logging system by using logging.setLoggerClass. With this setting, the logger objects instantiated from logging.getLogger will be of your class.
update with sample code based on request:
import logging
import threading
class MyLogger(logging.Logger):
def __init__(self, name, level = logging.NOTSET):
self._count = 0
self._countLock = threading.Lock()
return super(MyLogger, self).__init__(name, level)
@property
def warnCount(self):
return self._count
def warning(self, msg, *args, **kwargs):
self._countLock.acquire()
self._count += 1
self._countLock.release()
return super(MyLogger, self).warning(msg, *args, **kwargs)
logging.setLoggerClass(MyLogger)
logging.basicConfig()
'''testing below'''
logger = logging.getLogger('loggerX')
assert isinstance(logger, MyLogger)
logger.warning('1st warning')
logger.warning('2nd warning')
print logger.warnCount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With