Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new custom logger function in Python

I want to create new custom logger function. we have default functions available like below

    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')

How can create a new custom logger function using custom code. custom logger like below example -

logger.success('success message')

like image 567
Pu Ba Abhijit Avatar asked Sep 19 '25 23:09

Pu Ba Abhijit


1 Answers

Given that the current logging library doesn't really cater for this, the only way I can conceive that you'd be able to achieve what you are asking is to make a subclass of the logging.Logger class and define your own success method.

For example:

import logging

SUCCESS = 5
logging.addLevelName(5, 'SUCCESS')


class Logger(logging.Logger):
    super(logging.Logger)

    def success(self, msg, *args, **kwargs):
        if self.isEnabledFor(SUCCESS):
            self._log(SUCCESS, msg, args, **kwargs)


formatter = logging.Formatter('%(levelname)s - %(name)s - %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(formatter)

log = Logger('mycustomlogger')
log.setLevel(SUCCESS)
log.addHandler(ch)

log.success('Hello World')
like image 97
Vasili Syrakis Avatar answered Sep 22 '25 13:09

Vasili Syrakis