DEV Community

Cover image for Introduction to Logging in Python
Paulo GP
Paulo GP

Posted on

Introduction to Logging in Python

Introduction

Logging is an essential aspect of software development, allowing developers to track and record events that occur during the execution of a program. In Python, the logging module provides a flexible and customizable framework for logging messages of varying severity levels to different destinations.

Topics

  • Setting up logging configuration
  • Logging levels and their significance
  • Writing log messages
  • Logging to different destinations
  • Handling exceptions with logging

Setting up logging configuration

Python's logging module allows developers to configure logging behavior through code or configuration files. The configuration typically includes specifying the format of log messages, setting the logging level, and defining handlers for different output destinations.

import logging

logging.basicConfig(
    filename="example.log",
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.DEBUG
)
Enter fullscreen mode Exit fullscreen mode

Logging levels and their significance

Python logging supports several levels, each indicating the severity of the logged event. These levels include DEBUG, INFO, WARNING, ERROR, and CRITICAL. By setting the logging level, developers can control which messages get logged based on their importance.

import logging

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")
Enter fullscreen mode Exit fullscreen mode

Writing log messages

Developers can log messages using various methods provided by the logging module. These methods correspond to the different logging levels and allow for the inclusion of additional information such as variables or exceptions.

import logging

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.exception("Error occurred while dividing by zero")
Enter fullscreen mode Exit fullscreen mode

Logging to different destinations

Python logging supports logging to various destinations, including files, streams, and network sockets. By configuring different handlers, developers can send log messages to multiple destinations simultaneously.

import logging

console_handler = logging.StreamHandler()
file_handler = logging.FileHandler("example.log")

logger = logging.getLogger()
logger.addHandler(console_handler)
logger.addHandler(file_handler)

logger.warning("This message will be logged to both console and file")
Enter fullscreen mode Exit fullscreen mode

Handling exceptions with logging

In addition to logging messages, the logging module can be used to handle exceptions by logging the traceback information. This helps in debugging and troubleshooting issues encountered during program execution.

import logging

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.exception("Error occurred while dividing by zero")
Enter fullscreen mode Exit fullscreen mode

Examples

Setting up logging configuration

import logging

logging.basicConfig(
    filename="example.log",
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.DEBUG
)
Enter fullscreen mode Exit fullscreen mode

Logging levels and their significance

import logging

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")
Enter fullscreen mode Exit fullscreen mode

Writing log messages

import logging

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.exception("Error occurred while dividing by zero")
Enter fullscreen mode Exit fullscreen mode

Logging to different destinations

import logging

console_handler = logging.StreamHandler()
file_handler = logging.FileHandler("example.log")

logger = logging.getLogger()
logger.addHandler(console_handler)
logger.addHandler(file_handler)

logger.warning("This message will be logged to both console and file")
Enter fullscreen mode Exit fullscreen mode

Handling exceptions with logging

import logging

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.exception("Error occurred while dividing by zero")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Logging is a crucial aspect of software development, enabling developers to track and monitor the behavior of their applications. By leveraging Python's logging module, developers can effectively manage and analyze log messages to diagnose and troubleshoot issues encountered during program execution.

Top comments (0)