2

I have a simple script that I run as an exe file on Windows. However, when I am developing the script, I run it from the command line and use the logging module to output debug info to a log file. I would like to turn off the generation of the log file for my production code. How would I go about doing that?

This is the logging config I have setup now:

import logging

... 

 logging.basicConfig(filename='file.log',
        filemode="w",
        level=logging.DEBUG,
        format="%(asctime)s: %(name)s - %(levelname)s - %(message)s",
        datefmt='%d-%b-%y %H:%M:%S',
        )
...

logging.debug("Debug message")

1 Answer 1

1

If you don't mind the generation of an empty log file for production, you can simply increase the threshold of logging to a level above logging.DEBUG, such as logging.INFO, so that messages logged with logging.debug won't get output to the log file:

logging.basicConfig(filename='file.log', # creates an empty file.log
        filemode="w",
        level=logging.INFO,
        format="%(asctime)s: %(name)s - %(levelname)s - %(message)s",
        datefmt='%d-%b-%y %H:%M:%S',
        )

logging.debug("Debug message") # nothing would happen
logging.info("FYI") # logs 'FYI'

If you don't want logging to function at all, an easy approach is to override logging with a Mock object:

import logging
from unittest.mock import Mock

environment = 'production'

if environment == 'production':
    logging = Mock()

...

logging.basicConfig(...) # nothing would happen

logging.debug(...) # nothing would happen
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.