How to use the logging module in Python?

The logging module in Python is used to record the running log of an application. Here are the basic steps to use the logging module.

  1. Import the logging module.
import logging
  1. Set up the logger:
logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')
  1. Level: Set the logging level to DEBUG, INFO, WARNING, ERROR, or CRITICAL according to your needs.
  2. Set the name of the log file.
  3. filemode: specifies the opening mode for the log file, where ‘w’ means write-over and ‘a’ means append.
  4. Set the format of the logs, where ‘%(asctime)s’ represents the timestamp of the log record, ‘%(levelname)s’ represents the log level, and ‘%(message)s’ represents the log message.
  1. Keep a journal:
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
  1. debug(): Log debug level messages.
  2. info(): Log information level messages.
  3. notify(): log warnings.
  4. error(): logging the logs at the level of error.
  5. critical(): record logs of critical severity.
  1. Print logs in the console (optional):
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

After this configuration, in addition to writing the logs to a file, the logs will also be output to the console.

The above are the basic steps for using the logging module, which can be further configured and used according to actual needs.

bannerAds