Python Logging: A Deep Dive

To begin with what is this “logging” package you speak of? Well, my friend, it’s the holy grail for debugging your code and keeping track of all those ***** errors. It allows you to log messages to various destinations like files or stdout/stderr, and even lets you filter out certain types of logs based on their level (debug, info, warning, error, critical).

Now, let’s get our hands dirty with some code examples. Here’s a basic setup:

# Import the logging module
import logging

# Configure the logging settings
logging.basicConfig(filename='my_log.txt', level=logging.DEBUG)

# Define a function
def my_function():
    # Perform some calculations
    x = 10 / 3
    # Check if the result is infinity
    if x == float('inf'):
        # Log a critical message if the result is infinity
        logging.critical("Something went terribly wrong!")
    else:
        # Log an info message with the result if it is not infinity
        logging.info(f"The result is {x}")

In this example, we’re importing the `logging` module and setting up a basic configuration that logs to a file called “my_log.txt”. We also set the log level to DEBUG (which means it will log all messages at or above the debug level).

Next, those levels. Here’s what they mean:

– `DEBUG` Detailed information, typically of interest only when diagnosing problems.
– `INFO` Informational message (something that is useful to know but not essential)
– `WARNING` An indication that something unexpected happened or indicative of some problem in the near future (e.g., ‘disk space low’).
– `ERROR` Due to a more serious problem, the function or object cannot perform some function.
– `CRITICAL` A very serious error, indicating that the program itself may be unable to continue running.

So let’s say we have an issue with our code and want to log something at the critical level:

# Import the logging module
import logging

# Configure the logging settings, specifying the file to log to and the level of logging
logging.basicConfig(filename='my_log.txt', level=logging.DEBUG)

# Define a function called my_function
def my_function():
    # Perform some operation
    x = 10 / 3
    # Check if the result is infinity
    if x == float('inf'):
        # Log a critical message if the result is infinity
        logging.critical("Something went terribly wrong!")
    else:
        # Log an info message with the result if it is not infinity
        logging.info(f"The result is {x}")

In this example, we’re checking to see if our division by zero resulted in an infinite value (which it will). If so, we log a critical message that says “Something went terribly wrong!”.

But what if you don’t want all those logs cluttering up your file? Well, you can filter them out based on their level. Here’s how:

# Import the logging module
import logging

# Configure the logging settings
logging.basicConfig(filename='my_log.txt', level=logging.DEBUG)

# Define a function
def my_function():
    # Do something here...
    # Divide 10 by 3 and assign the result to x
    x = 10 / 3

    # Check if x is equal to infinity
    if x == float('inf'):
        # If x is infinity, log a critical message
        logging.critical("Something went terribly wrong!")
    else:
        # If x is not infinity, log an info message with the result
        logging.info(f"The result is {x}")

    # Check if x is greater than 5
    if x > 5:
        # If x is greater than 5, log a warning message
        logging.warning(f"The result ({x}) is too high.")

In this example, we’re checking to see if our division resulted in a value greater than 5 (which it won’t). If so, we log a warning message only when the result is greater than 5. This way, you can keep your logs clean and focused on what matters most.

And that’s pretty much all there is to Python logging! It may seem like overkill at first, but trust me once you start using it in earnest, you won’t know how you ever lived without it.

SICORPS