Ashish
Ashish

Reputation: 479

Python : change numeric values of logging levels

The default Numeric values of logging levels is :

enter image description here

I need to change this values and set the DEBUG value to 20 and INFO to 10

Please let me know how to do it.

At present this is my code :

log =logging.getLogger(__name__)

log.setLevel(logging.DEBUG)
formatter =logging.Formatter('[%(module)s](%(lineno)d) [%(levelname)s] : %(message)s')

file_handler = logging.FileHandler('debug.log', mode='w')
file_handler.setFormatter(formatter)
log.addHandler(file_handler)


stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)


log.warning('This is a warning')
log.error('This is an error')
log.info('This is an INFO')
log.debug('This is an DEBUG')
log.critical('This is an CRITICAL')

Upvotes: 1

Views: 619

Answers (2)

Ashish
Ashish

Reputation: 479

This is how I solved

I created a filter like this :

class debugFilter(logging.Filter):
    def filter(self, record):
        if (record.levelno == 10):
            return True
        else:
            return False

and main code :

file_handler = logging.FileHandler('debug.log', mode='w')
file_handler.addFilter(debugFilter())
file_handler.setFormatter(formatter)
log.addHandler(file_handler)

Upvotes: 0

Dan D.
Dan D.

Reputation: 74655

You can use a filter on the handler instead which can select messages with a specific level.

See logging with filters

The body of the filter method on the Filter subclass in this case would be:

return record.getLevel() == logging.DEBUG

Upvotes: 1

Related Questions