DEV Community

Arthur
Arthur

Posted on

Python Logging Tutorial: How to Track Errors and Debug Applications

Hello, I'm Arthur. Have you ever written a Python script that worked perfectly yesterday but suddenly failed today?

Maybe it stopped processing files, returned an unexpected result, or crashed without explaining what went wrong.

When you're working with larger applications, using print() statements everywhere can make debugging difficult.

Python's built-in logging module provides a better way to record application activity, track errors, and understand what happened when something failed.

In this tutorial, we'll build a practical logging system that you can use in your own Python projects.

1. Understand Why Logging Matters

Logging allows your application to record important events while it runs.

For example, you might want to know:

  • When an application starts or stops
  • Which files were processed
  • Whether an API request failed
  • Why a database connection could not be established
  • When an unexpected error occurred

Instead of displaying every message on the screen, you can save important information in a log file and review it later.

Python already includes a logging module, so you do not need to install an additional package.

2. Create Your First Log Messages

Create a Python file named app.py:

import logging

logging.basicConfig(level=logging.INFO)

logging.debug("This is a debugging message")
logging.info("Application started")
logging.warning("Disk space is getting low")
logging.error("Unable to process the request")
Enter fullscreen mode Exit fullscreen mode

Run the script:

python3 app.py
Enter fullscreen mode Exit fullscreen mode

You will see the informational, warning, and error messages.

The debug message will not appear because the logging level is set to INFO.

Python supports five standard logging levels:

Level Purpose
DEBUG Detailed information for troubleshooting
INFO Confirmation that something worked
WARNING An unexpected situation that may need attention
ERROR A problem that prevented an operation
CRITICAL A serious failure that may stop the application

Choosing the correct level helps you understand which events require attention.

3. Save Logs to a File

For applications running on a server, saving logs to a file is often more useful than displaying them in a terminal.

Update your logging configuration:

import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("Application started")
logging.warning("A configuration value is missing")
Enter fullscreen mode Exit fullscreen mode

Run the script again.

A file named app.log will be created in the current working directory.

The log entries will include a timestamp, the logging level, and the message.

Example:

2026-11-27 10:30:00,000 - INFO - Application started
2026-11-27 10:30:01,000 - WARNING - A configuration value is missing
Enter fullscreen mode Exit fullscreen mode

Timestamps are particularly useful when investigating problems that occur only at certain times.

4. Record Python Exceptions Properly

One of the most useful logging features is the ability to record exception details.

Consider a script that reads a configuration file:

import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO
)

try:
    with open("config.json") as file:
        data = file.read()

except FileNotFoundError:
    logging.exception("Configuration file could not be found")
Enter fullscreen mode Exit fullscreen mode

If the file does not exist, the application will record the error and its traceback.

The traceback helps you identify where the exception occurred.

The logging.exception() method should be used inside an exception handler.

This is more useful than writing only the error message because the traceback provides additional debugging information.

5. Use Logging in a Real Python Function

Let's create a simple function that processes a list of user records.

import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

def process_users(users):
    logging.info("Starting user processing")

    for user in users:
        try:
            name = user["name"]
            logging.info("Processed user: %s", name)

        except KeyError:
            logging.warning("A user record is missing the name field")

    logging.info("User processing completed")


users = [
    {"name": "Alex"},
    {"name": "Sarah"},
    {"email": "example@email.com"}
]

process_users(users)
Enter fullscreen mode Exit fullscreen mode

This example records the processing of each user and warns when a record is missing the expected field.

Notice the use of %s in the logging message.

Python's logging module can format the message only when it needs to be emitted. This is generally preferable to constructing every message with an f-string, especially when debug messages are disabled.

6. Configure Logging for a Server Application

When a Python application runs on a VPS, logs become especially useful because you may not be watching the terminal continuously.

For example, you could use the following configuration:

import logging

logging.basicConfig(
    filename="/var/log/myapp/app.log",
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s"
)

logger = logging.getLogger(__name__)

logger.info("Application started")
Enter fullscreen mode Exit fullscreen mode

Before using this path, create the directory and make sure the application user has permission to write to it.

For a production application, consider log rotation so that log files do not consume unlimited disk space.

You should also avoid recording passwords, API keys, access tokens, or other sensitive information in your logs.

7. Check Logs When an Application Fails

When your application runs on a Linux server, you can inspect its log file using:

tail -f /var/log/myapp/app.log
Enter fullscreen mode Exit fullscreen mode

This displays new log entries as they are written.

To search for error messages:

grep "ERROR" /var/log/myapp/app.log
Enter fullscreen mode Exit fullscreen mode

If your Python application runs through a systemd service, you can also check its logs with:

sudo journalctl -u myapp.service -n 100
Enter fullscreen mode Exit fullscreen mode

Replace myapp.service with your actual service name.

These commands can help you investigate problems without repeatedly restarting the application.

8. Practice With a Small Project

A useful way to learn logging is to add it to a script you already use.

Try creating a Python program that:

  1. Reads a CSV file.
  2. Records when processing starts.
  3. Logs the number of records processed.
  4. Records any rows that contain missing values.
  5. Writes a final summary to the log file.

Then deliberately introduce an error and check whether your logs provide enough information to understand what happened.

This exercise will help you learn how logging works in a real application rather than only memorizing commands.

Final Thoughts

Logging is a practical Python skill that becomes increasingly important as your applications grow.

It helps you understand what your code is doing, investigate unexpected behavior, and troubleshoot problems after deployment.

If you're planning to run Python applications on a Linux server, you can explore Seimaxim VPS hosting when comparing server environments for your projects.

The important thing is to start using logging early, choose meaningful log levels, and record enough information to understand failures without exposing sensitive data.

For your next Python project, try replacing a few debugging print() statements with structured logging. You'll quickly see the difference.

Top comments (0)