Logging with Loguru

The Problem

Different things happen inside your application. Sometimes something fails, so you start adding print statements to see what’s going on at different stages. Then you have to remove them, before you reach production. But suddenly you realize that you actually want this information in production, too. We see where it goes.

The Solution

What you actually want is a logging system. The earlier you start using it, the lesser the pain later on.

Good logging systems provide you with a lot of features, such as:

  • Different log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  • Log to different outputs (console, file, database, etc.)
  • Log to different formats (plain text, JSON, etc.)
  • Is already configured for you

In tapyr, we use Loguru. It’s a Python logging library that provides a simple and powerful logging experience. It is easy to use and configure, and it provides structured logging out of the box.

Check out the repository for more information on how to use Loguru.

How to use it

The logger is configured in the app.py file. But you can use it in any file you want simply by importing it.

from loguru import logger

logger.debug("This is a debug message")

For example in the tapyr_template/logic/utils.py file, you can also see the @logger.catch decorator in action. For more information, check out the Loguru documentation.