Loguru: A Concise logging solution

Sachinjose
3 min readJun 9, 2024

--

Photo by Dalle

While I was engaged in a Python project, I considered investigating alternative logging options. Although the conventional logging module is quite effective, I was in search of an enhanced solution. During my research, I discovered an impressive module known as Loguru.

In this article, I will delve into my journey with Loguru, detailing its features, benefits, and installation instructions.

Install Loguru

Before you can start using Loguru module, you need to install it. You can install Loguru using the pip command:

pip install loguru

How to Use Python Loguru

Utilizing Python’s Loguru library is straightforward. You only need to import the loguru package and utilize its logger instance to carry out logging tasks.

from loguru import logger

logger.trace("TRACE")
logger.debug("DEBUG")
logger.info("INFO")
logger.success("SUCCESS")
logger.warning("WARNING")
logger.error("ERROR")
logger.critical("CRITICAL")

Loguru defaults to using DEBUG as its minimum level, which causes any logs with a severity lower than DEBUG to be ignored.

If you want to change the default level, you may use the level argument to the add() method shown below:

logger.add(sys.stderr, level="INFO")

Custom logger levels

In addition to the predefined logging levels in Loguru, it is possible to create custom log levels for use as demonstrated below.

import sys
from loguru import logger
logger.level("FATAL", no=60, color="<red>", icon="!!!")
logger.log("FATAL", "A user updated some information.")

Adding handlers

Handlers can be controlled to either print logs to the console or store them in a log file, as demonstrated below.

import sys
from loguru import logger

format = "{time:HH:mm:ss.ss} | {level: <8} | {file: ^8} | {function: ^15} | {line: >3} | <level> {message} </level>"
log_file = "logger.log"
logger.add(sys.stderr, format=format, level="INFO")
logger.add(log_file, format=format, level="INFO")

To add coloring to the console logs,

import sys
from loguru import logger

format = "{time:HH:mm:ss.ss} | {level: <8} | {file: ^8} | {function: ^15} | {line: >3} | <level> {message} </level>"
log_file = "logger.log"
logger.add(sys.stderr, format=format, level="INFO", colorize=True)

To direct logs of a specific level to a separate file, use as below. This was helpful to me when I wanted to store only the error logs into a seperate file.

import sys
from loguru import logger
logger.add(log_file, filter=lambda record: record["level"].name=="ERROR", Serialize=True)

Exceptions catching

By using the logger wrapper, we can perform exception handling. This avoids use of try/except block explicitly.

@logger.catch(level="CRITICAL", message="Error in division.")
def division(a, b):
return a/b

division(10, 0)

Output:-

Extra Insights

Rotation of Logs

Using rotation in the handler, new log file will be generated based it.

. . .
logger.add("logger.log", rotation="60 seconds")

For example, new log file will be generated every 60 seconds. After every 60 seconds, the file is renamed to logger.<timestamp>.log and a new loguru.log file is created afterward.

Wrapper function

One of the sample wrapper function that came in handy is to log the total time taken for executing a method

import functools
from loguru import logger


def timeit(func):
def wrapped(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
logger.debug("Function '{}' executed in {:f} s", func.__name__, end - start)
return result

return wrapped


# To use the created wrapper
@timeit()
def foo(a, b, c):
logger.info("Inside the function")
return a * b * c

As we sign off about the Python Loguru module, let’s not forget that in the realm of coding, every line tells a story, and every log captures an epic tale.

Keep your spirits up and your log levels down and let the chronicles of your code be as legendary as the myths of old. Until we code again,

happy logging!

--

--