Thursday, October 9, 2025
HomePythonAn Intro to Logging with Python and Loguru

An Intro to Logging with Python and Loguru


Python’s logging module isn’t the one technique to create logs. There are a number of third-party packages you should use, too. One of the crucial common is Loguru. Loguru intends to take away all of the boilerplate you get with the Python logging API.

You will see that Loguru enormously simplifies creating logs in Python.

This chapter has the next sections:

  • Set up
  • Logging made easy
  • Handlers and formatting
  • Catching exceptions
  • Terminal logging with shade
  • Straightforward log rotation

Let’s learn how a lot simpler Loguru makes logging in Python!

Earlier than you can begin with Loguru, you have to to put in it. In spite of everything, the Loguru bundle doesn’t include Python.

Fortuitously, putting in Loguru is straightforward with pip. Open up your terminal and run the next command:

python -m pip set up loguru

Pip will set up Loguru and any dependencies it might need for you. You should have a working bundle put in when you see no errors.

Now let’s begin logging!

Logging with Loguru could be finished in two strains of code. Loguru is de facto that easy!

Don’t imagine it? Then open up your Python IDE or REPL and add the next code:

# hey.py

from loguru import logger

logger.debug("Good day from loguru!")
logger.data("Knowledgeable from loguru!")

One import is all you want. Then, you’ll be able to instantly begin logging! By default, the log will go to stdout.

Right here’s what the output seems like within the terminal:

2024-05-07 14:34:28.663 | DEBUG    | __main__:<module>:5 - Good day from loguru!
2024-05-07 14:34:28.664 | INFO     | __main__:<module>:6 - Knowledgeable from loguru!

Fairly neat! Now, let’s learn how to alter the handler and add formatting to your output.

Loguru doesn’t consider handlers the way in which the Python logging module does. As an alternative, you employ the idea of sinks. The sink tells Loguru the best way to deal with an incoming log message and write it someplace.

Sinks can take plenty of completely different kinds:

  • A file-like object, reminiscent of sys.stderr or a file deal with
  • A file path as a string or pathlib.Path
  • callable, reminiscent of a easy perform
  • An asynchronous coroutine perform that you just outline utilizing async def
  • A built-in logging.Handler. In the event you use these, the Loguru information convert to logging information routinely

To see how this works, create a brand new file referred to as file_formatting.py in your Python IDE. Then add the next code:

# file_formatting.py

from loguru import logger

fmt = "{time} - {identify} - {degree} - {message}"

logger.add("formatted.log", format=fmt, degree="INFO")
logger.debug("It is a debug message")
logger.data("That is an informational message")

If you wish to change the place the logs go, use the add() technique. Be aware that this provides a brand new sink, which, on this case, is a file. The logger will nonetheless log to stdout, too, as that’s the default, and you might be including to the handler listing. If you wish to take away the default sink, add logger.take away() earlier than you name add().

If you name add(), you’ll be able to cross in a number of completely different arguments:

  • sink – The place to ship the log messages
  • degree – The logging degree
  • format – Easy methods to format the log messages
  • filter – A logging filter

There are a number of extra, however these are those you’d use probably the most. If you wish to know extra about add(), you need to try the documentation.

You might need observed that the formatting of the log information is somewhat completely different than what you noticed in Python’s personal logging module.

Here’s a itemizing of the formatting directives you should use for Loguru:

  • elapsed – The time elapsed because the app began
  • exception – The formatted exception, if there was one
  • further – The dict of attributes that the person certain
  • file – The identify of the file the place the logging name got here from
  • perform – The perform the place the logging name got here from
  • degree – The logging degree
  • line – The road quantity within the supply code
  • message – The unformatted logged message
  • module – The module that the logging name was made out of
  • identify – The __name__ the place the logging name got here from
  • course of – The method wherein the logging name was made
  • thread – The thread wherein the logging name was made
  • time – The conscious native time when the logging name was made

You may as well change the time formatting within the logs. On this case, you’d use a subset of the formatting from the Pendulum bundle. For instance, when you needed to make the time exclude the date, you’d use this: {time:HH:mm:ss} fairly than merely {time}, which you see within the code instance above.

See the documentation for particulars on formating time and messages.

If you run the code instance, you will note one thing just like the next in your log file:

2024-05-07T14:35:06.553342-0500 - __main__ - INFO - That is an informational message

Additionally, you will see log messages despatched to your terminal in the identical format as you noticed within the first code instance.

Now, you’re prepared to maneuver on and find out about catching exceptions with Loguru.

Catching exceptions with Loguru is finished by utilizing a decorator. Chances are you’ll do not forget that while you use Python’s personal logging module, you employ logger.exception within the besides portion of a attempt/besides assertion to file the exception’s traceback to your log file.

If you use Loguru, you employ the @logger.catch decorator on the perform that comprises code that will increase an exception.

Open up your Python IDE and create a brand new file named catching_exceptions.py. Then enter the next code:

# catching_exceptions.py

from loguru import logger

@logger.catch
def silly_function(x, y, z):
    return 1 / (x + y + z)

def primary():
    fmt = "{time:HH:mm:ss} - {identify} - {degree} - {message}"
    logger.add("exception.log", format=fmt, degree="INFO")
    logger.data("Utility beginning")
    silly_function(0, 0, 0)
    logger.data("Completed!")

if __name__ == "__main__":
    primary()

In accordance with Loguru’s documentation, the’ @logger.catch` decorator will catch common exceptions and likewise work with purposes with a number of threads. Add one other file handler on high of the stream handler and begin logging for this instance.

You then name silly_function() with a bunch of zeroes, which causes a ZeroDivisionError exception.

Right here’s the output from the terminal:

In the event you open up the exception.log, you will note that the contents are somewhat completely different since you formatted the timestamp and likewise as a result of logging these humorous strains that present what arguments have been handed to the silly_function() don’t translate that nicely:

14:38:30 - __main__ - INFO - Utility beginning
14:38:30 - __main__ - ERROR - An error has been caught in perform 'primary', course of 'MainProcess' (8920), thread 'MainThread' (22316):
Traceback (most up-to-date name final):

  File "C:books11_logurucatching_exceptions.py", line 17, in <module>
    primary()
    â”” <perform primary at 0x00000253B01AB7E0>

> File "C:books11_logurucatching_exceptions.py", line 13, in primary
    silly_function(0, 0, 0)
    â”” <perform silly_function at 0x00000253ADE6D440>

  File "C:books11_logurucatching_exceptions.py", line 7, in silly_function
    return 1 / (x + y + z)
                │   │   └ 0
                │   └ 0
                â”” 0

ZeroDivisionError: division by zero
14:38:30 - __main__ - INFO - Completed!

On the entire, utilizing the @logger.catch is a pleasant technique to catch exceptions.

Now, you’re prepared to maneuver on and find out about altering the colour of your logs within the terminal.

Terminal Logging with Shade

Loguru will print out logs in shade within the terminal by default if the terminal helps shade. Colourful logs could make studying by means of the logs simpler as you’ll be able to spotlight warnings and exceptions with distinctive colours.

You should utilize markup tags so as to add particular colours to any formatter string. You may as well apply daring and underline to the tags.

Open up your Python IDE and create a brand new file referred to as terminal_formatting.py. After saving the file, enter the next code into it:

# terminal_formatting.py
import sys
from loguru import logger

fmt = ("<purple>{time}</purple> - "
       "<yellow>{identify}</yellow> - "
       "{degree} - {message}")

logger.add(sys.stdout, format=fmt, degree="DEBUG")
logger.debug("It is a debug message")
logger.data("That is an informational message")

You create a particular format that units the “time” portion to purple and the “identify” to yellow. Then, you add() that format to the logger. You’ll now have two sinks: the default root handler, which logs to stderr, and the brand new sink, which logs to stdout. You do formatting to match the default colours to your customized ones.

Go forward and run the code. It’s best to see one thing like this:

Changing terminal output colors with Loguru

Neat! It might be greatest when you now spent a number of moments finding out the documentation and attempting out a few of the different colours. For instance, you should use hex and RGB colours and a handful of named colours.

The final part you’ll take a look at is the best way to do log rotation with Loguru!

Loguru makes log rotation simple. You don’t have to import any particular handlers. As an alternative, you solely have to specify the rotation argument while you name add().

Listed below are a number of examples:

  • logger.add("file.log", rotation="100 MB")
  • logger.add("file.log", rotation="12:00")
  • logger.add("file.log", rotation="1 week")

These reveal that you could set the rotation at 100 megabytes at midday each day and even rotate weekly.

Open up your Python IDE so you’ll be able to create a full-fledged instance. Title the file log_rotation.py and add the next code:

# log_rotation.py

from loguru import logger

fmt = "{time} - {identify} - {degree} - {message}"

logger.add("rotated.log",
           format=fmt,
           degree="DEBUG",
           rotation="50 B")
logger.debug("It is a debug message")
logger.data("That is an informational message")

Right here, you arrange a log format, set the extent to DEBUG, and set the rotation to each 50 bytes. If you run this code, you’re going to get a few log recordsdata. Loguru will add a timestamp to the file’s identify when it rotates the log.

What if you wish to add compression? You don’t have to override the rotator such as you did with Python’s logging module. As an alternative, you’ll be able to activate compression utilizing the compression argument.

Create a brand new Python script referred to as log_rotation_compression.py and add this code for a completely working instance:

# log_rotation_compression.py

from loguru import logger

fmt = "{time} - {identify} - {degree} - {message}"

logger.add("compressed.log",
           format=fmt,
           degree="DEBUG",
           rotation="50 B",
           compression="zip")
logger.debug("It is a debug message")
logger.data("That is an informational message")
for i in vary(10):
    logger.data(f"Log message {i}")

The brand new file is routinely compressed within the zip format when the log rotates. There’s additionally a retention argument that you should use with add() to inform Loguru to wash the logs after so many days:

logger.add("file.log",
             rotation="100 MB",
             retention="5 days")

In the event you have been so as to add this code, the logs that have been greater than 5 days outdated would get cleaned up routinely by Loguru!

The Loguru bundle makes logging a lot simpler than Python’s logging library. It removes the boilerplate wanted to create and format logs.

On this chapter, you realized concerning the following:

  • Set up
  • Logging made easy
  • Handlers and formatting
  • Catching exceptions
  • Terminal logging with shade
  • Straightforward log rotation

Loguru can do far more than what is roofed right here, although. You may serialize your logs to JSON or contextualize your logger messages. Loguru additionally means that you can add lazy analysis to your logs to forestall them from affecting efficiency in manufacturing. Loguru additionally makes including customized log ranges very simple. For full particulars about all of the issues Loguru can do, you need to seek the advice of Loguru’s web site.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments