Python excellent third-party asynchronous log library loguru introduction

I. Introduction

In the process of writing and debugging Python code, we often need to record logs. Usually we use the built-in standard library logging that comes with python, but using this library, the configuration is more cumbersome. In order to improve programming efficiency, this article focuses on a recently discovered treasure third-party log library Loguru. The name of the library comes from Hindi and means log master.

Let's first make an intuitive comparison to illustrate the elegance of Loguru. Using the logging that comes with python, the sample code is as follows:

20221221220533

Sample output is as follows:

20221221220709

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

20221221220734

Use Loguru to output the log, and the log with color will appear after the terminal is executed, and it is super convenient to use.

Two, install loguru

Just use pip to install directly, the command is as follows:

pip install loguru

Output to the terminal using:

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

Output to file usage:

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

3. Features

Refer to the official github, which gives the rich features of the Loguru library. Here are a few important features to explain

3.1 Out of the box

The original intention of the Loguru library design is to pursue one and only one logger. For the convenience of use, the output style is preset in advance. If you need to print the log, you only need to take the following method:

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

3.2 Import function can be used without initialization

In Loguru, how can we customize the output style? How to filter output information? How to set log level?

The answer is to call the add() function

logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")

Examples are as follows:

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

We check info.log, the results are as follows:

20221221221253

3.3 Easier file logging and dump/retain/compress methods

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

logger.add("file_1.log", rotation="500 MB")    # 文件过大(超过500M)就会重新生成一个文件
logger.add("file_2.log", rotation="12:00")     # 每天12点创建新文件
logger.add("file_3.log", rotation="1 week")    # 文件时间过长就会创建新文件
logger.add("file_4.log", retention="10 days")  # 一段时间后会清空
logger.add("file_5.log", compression="zip")    # 保存zip格式

3.4 More elegant string formatted output

The Loguru library is more powerful in processing strings. String formatted output supports {} to replace %. The function is similar to str.format()

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

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

We often encounter that when the code crashes, we can't see any error information in the log. In the Loguru library, the @logger.catch decorator can be used to ensure that the error message is saved when an exception occurs.

Examples are as follows:

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

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

20221221221625

3.6 Can support custom colors

Loguru supports custom colors. If you don't like its default colors, you can change them like this:

logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")

3.7 Support asynchronous, thread and multi-process safe

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

logger.add("somefile.log", enqueue=True)

3.8 Support exception integrity description

For logs, a log without an error stack is soulless. Loguru allows displaying the entire stack trace to help you spot problems (including variables).

logger.add("out.log", 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:
        logger.exception("What?!")

nested(0)

The result of the operation is as follows:

20221221222054

3.9 Better datetime handling

We can customize the date output style as follows:

logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")  #定义日期样式

3.10 Support email notification

Loguru can be used in conjunction with the powerful notifiers library to receive emails when programs fail unexpectedly, or to send many other types of notifications.

import notifiers

params = {
    "username": "[email protected]",
    "password": "abc123",
    "to": "[email protected]"
}

# 初始化时发送一封邮件
notifier = notifiers.get_notifier("gmail")
notifier.notify(message="The application is running!", **params)

# 发生Error时,发邮件进行告警
from notifiers.logging import NotificationHandler

handler = NotificationHandler("gmail", defaults=params)
logger.add(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.

Four. Summary

This article gives a brief overview of the main features of the Loguru library. If you need to know more about its features, please refer to the official github.

It is recommended that you use the Loguru library for log processing in your daily life.

loguru official website: https://loguru.readthedocs.io/en/stable/index.html
api documentation: https://loguru.readthedocs.io/en/stable/api.html
project address: https://github. com/Delgan/loguru

This article is reproduced from https://zhuanlan.zhihu.com/p/397181586

Guess you like

Origin blog.csdn.net/hubing_hust/article/details/128402860