Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn off logging statements without removing them from the code

If there are logging statements spread throughout a codebase, how do I set up the logger so I don't have to comment out each call to the logger when deploying the code into production?

Here's my current code:

import logging


logging.basicConfig(filename='./example.log', level=logging.DEBUG, 
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M')

logging.debug('debug failed')
logging.info('info failed')
logging.warning('A warning')
like image 298
Merlin Avatar asked Sep 18 '12 18:09

Merlin


People also ask

Why is logging better than printing?

One of the advantages of using the logging module to track our codes is the ability to format the messages based on our needs. For example, in my code, I would like to log the date and time with appropriate messages. Here is an example. And here is the output.

What is Loglevel?

A log level or log severity is a piece of information telling how important a given log message is. It is a simple, yet very powerful way of distinguishing log events from each other. If the log levels are used properly in your application all you need is to look at the severity first.

What are the different log levels?

Logging levels explained. The most common logging levels include FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL, and OFF. Some of them are important, others less important, while others are meta-considerations.


1 Answers

Instead of using the basicConfig, you can set up the logger more explicitly with the handlers you want, based on any criteria.

import logging

log = logging.getLogger("FOO")
log.setLevel(logging.DEBUG)

# needs a handler
log.info('info')
#No handlers could be found for logger "FOO"

ch = logging.StreamHandler()
log.addHandler(ch)
log.info('info')
# info

log.removeHandler(ch)

noop = logging.NullHandler()
log.addHandler(noop)
# nothing happens here
log.info('info')

You can have a conditional statement that either adds the handler you want if you are running in debug mode, or you can add a NullHandler that just absorbs the log messages. You can also configure the levels individually of each handler, so that you would always see warnings and above. Each handler can have its own level, in addition to the main logger.

You can refer to the tutorials on how to get more specific with levels, handlers, and formatting.

like image 157
jdi Avatar answered Sep 19 '22 12:09

jdi