Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override method of the logging module

Tags:

python

django

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.

like image 210
Prashant_DevOps10 Avatar asked May 04 '16 10:05

Prashant_DevOps10


People also ask

How do I override a python logger?

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.

What does logging module do in Python?

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.

What is the default level in logging module?

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.


1 Answers

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
like image 153
Lei Shi Avatar answered Sep 27 '22 23:09

Lei Shi