ilogging

Python Logging

Python Logging

Logging is an essential part of any program to track its execution, report errors, and store other relevant information. The logging module is used to log messages.

Basic Logging

You can log messages using different levels: DEBUG, INFO, WARNING, ERROR, and CRITICAL.

      
        import logging

        logging.basicConfig(level=logging.DEBUG)
        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")
      
    

This code sets up logging and logs messages of various severity levels.

Logging to a File

You can also log messages to a file:

      
        logging.basicConfig(filename='app.log', level=logging.DEBUG)
        logging.info("Logging to a file now.")
      
    

By setting filename, the log messages will be written to a file instead of the console.

Activity

Try It Yourself!

Set up logging for an application that logs user login attempts with timestamps.

Quick Quiz

Quick Quiz

  1. What is the default logging level in Python?
  2. How can you log messages to a file in Python?

Answers: The default logging level is WARNING. You can log messages to a file by setting the filename parameter in basicConfig().