SoFunction
Updated on 2024-11-20

Introduction to loguru, a third-party asynchronous logging library for python

I. Introduction

In the process of writing and debugging Python code, we often need to record logs, usually we will use python comes with the built-in standard library logging, but the use of the library, the configuration is more cumbersome. In order to improve programming efficiency, this article focuses on the recent discovery of a treasure third-party logging library Loguru, the name of the library comes from the Indian language, meaning log master.

Let's do a visual comparison to illustrate the elegance of Loguru. Using python's own logging, the sample code is as follows:

20221221220533

The sample output is as follows:

20221221220709

Using the Loguru library, the sample code is as follows:

20221221220734

Using Loguru to output logs, logs with colors appear after terminal execution and are super easy to use.

II. Installation of loguru

Installation can be done directly using pip with the following command:

pip install loguru

Output to end-use mode:

from loguru import logger
("msg msg msg!")

Output to file usage:

from loguru import logger
("file_name.log")
("msg msg msg!")

III. Characteristics

Referring to the official github, which gives a rich set of features for the Loguru library, here is a selection of the most important ones.

3.1 Out of the box

Loguru library is designed to pursue the original intention of having only one logger, in order to use the convenience of the output style is preset in advance. If you need to print the log only need to take the following way:

from loguru import logger
("That's it, beautiful and simple logging!")

3.2 No initialization required, import function ready to use

How can we customize the output style in Loguru? How to filter the output information? How to set log level?

The answer is to call the add() function

(, format="{time} {level} {message}", filter="my_module", level="INFO")

Examples are shown below:

from loguru import logger
("", format="{time} {level} {message}", filter="", level="INFO")
("This is a debug msg")
("This is a info msg")

We checked and the results were as follows.

20221221221253

3.3 Easier file logging and dumping/retention/compression methods

We can make log saving more user-friendly by simple configuration. For example, if we want to delete old logs, or if we want to automatically compress the saved logs, we can refer to the following commands:

("file_1.log", rotation="500 MB")    # File is too large (over 500M) then a new file is generated
("file_2.log", rotation="12:00")     # New documents created at 12:00 a.m. every day
("file_3.log", rotation="1 week")    # New files are created when the file is too long
("file_4.log", retention="10 days")  # It'll clear up after a while
("file_5.log", compression="zip")    # save (a file etc) (computing)zipspecification

3.4 More Elegant String Formatting Output

The Loguru library has more powerful string processing capabilities. The string formatted output supports {} as a replacement for %, which is similar to ().

("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")

3.5 Exceptions can be caught in the thread or in the main thread

We often encounter code that crashes and we don't see any error messages in the log. In the Loguru library, the @ decorator can be used to ensure that error messages are saved when an exception occurs.

Examples are shown below:

@
def main(x, y, z):
    return x * y / z

res = main(1,2,0)
print(res)

20221221221625

3.6 Custom colors can be supported

Loguru does support custom colors, so if you don't like its default color, you can change it this way:

(, colorize=True, format="<green>{time}</green> <level>{message}</level>")

3.7 Asynchronous support and thread and multi-process safety

Loguru is thread-safe by default, but it is not multi-process safe. However, if you need multi-process/asynchronous logging, it can support that, just add an enqueue parameter:

("", enqueue=True)

3.8 Support for Exception Integrity Description

As far as logs are concerned, a log without an error stack is soulless. loguru allows displaying the entire stack information to help you find problems (including variables).

("", backtrace=True, diagnose=True)  # Caution, may leak sensitive data in prod

def func(a, b):
    return a / b

def nested(c):
    try:
        func(5, c)
    except ZeroDivisionError:
        ("What?!")

nested(0)

The results are as follows.

20221221222054

3.9 Better date-time handling

We can customize the date output style as shown below:

("", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")  #Defining Date Styles

3.10 Support for e-mail notification

Loguru can be used in conjunction with the notifiers library, a powerful email notification module, to receive emails when a program fails unexpectedly, or to send many other types of notifications.

import notifiers

params = {
    "username": "you@",
    "password": "abc123",
    "to": "dest@"
}

# Send an email on initialization
notifier = notifiers.get_notifier("gmail")
(message="The application is running!", **params)

# Send an e-mail alert when an Error occurs.
from  import NotificationHandler

handler = NotificationHandler("gmail", defaults=params)
(handler, level="ERROR")

After this configuration, every time an Error log is generated, the program will automatically send a notification email to your mailbox, which is really user-friendly enough.

IV. Summary

This article provides a brief overview of the main features of the Loguru library. For a more detailed description of its features, please refer to the official github.

We recommend that you use the Loguru library more often in your daily life for logging work.

Loguru Official Website./en/stable/
api documentation./en/stable/
Project Address:/Delgan/loguru

to this article on the python excellent third-party asynchronous logging library loguru introduction to this article, more related python asynchronous logging library loguru content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!