New logging skills in Python

Keywords: Python

Introduction: continuous learning, continuous evolution, get logging new skills

In general, we often use the logging module to record logs. Before using it, we need to configure the template and set the Handler and Formatter to preprocess, such as log output location, output format, log blocking and backup. When using logs in different projects, you need to configure the logger in the early stage. Compared with the new skills of get today, I feel that the configuration is cumbersome.

The new skill is "Delgan/loguru", Loguru is a library which aims to bring enjoyable logging in Python

In this article, we introduce Loguru from four aspects:

1. Different from logging, why is loguru "fragrant"

2. Installation

3. Quick use

4. Introduction to high-order usage

1, Different from logging, why is loguru "fragrant"

logging

loguru

identical

Provide simple and flexible event recording function

Different

You need to explicitly instantiate the logger and use handler, format and filter

Reduce the configuration steps, and the add function rules all

2, Installation

As the old rule, the first step is to install the library. In the python 3 environment, you can directly install pip3

pip3 install loguru

3, Quick use

After the installation is successful, we can start

from loguru import logger

logger.debug("This is Debug")

There is no need for cumbersome configuration, so easy

The main object in loguru is logger. There is only loguru. Why not configure it? That's because these configurations have been pre configured. Output formatting, text color, etc. the console output is as follows:

The output content includes time, level, module name, line number and log information. In addition, the output is color, which will look better

How to customize DIY's personalized log? Let's take a look at the next chapter

4, Introduction to high-order usage

Let's mainly look at the "universal" add() of loguru.logger

def add(
        self,
        sink,
        *,
        level=_defaults.LOGURU_LEVEL,
        format=_defaults.LOGURU_FORMAT,
        filter=_defaults.LOGURU_FILTER,
        colorize=_defaults.LOGURU_COLORIZE,
        serialize=_defaults.LOGURU_SERIALIZE,
        backtrace=_defaults.LOGURU_BACKTRACE,
        diagnose=_defaults.LOGURU_DIAGNOSE,
        enqueue=_defaults.LOGURU_ENQUEUE,
        catch=_defaults.LOGURU_CATCH,
        **kwargs
    ):
  pass

  From the source code, we can see that there are many add parameters, such as level, format, filter, color, etc. Let's focus on the sink parameter

sink : |file-like object|_, |str|, |Path|, |callable|_, |coroutine function|_ or |Handler|

An object in charge of receiving formatted logging messages and propagating them to an

appropriate endpoint.

(1) Support for file objects

(2) You can pass in one directly   str   String or   pathlib.Path   object

(3) It can be a Handler in the logging module

(4) It can be a class or method

Let's try it

(1) Save output log to file

from loguru import logger

logger.add("test_loguru_{time}.log")  # Define the file name of the output in add

logger.debug("This is Debug")

  console output

Output the file to the current project directory

File content

(2) Support log size segmentation and log retention time definition

Create by log size, time (hours, weeks)

rotation : |str|, |int|, |time|, |timedelta| or |callable|_, optional

A condition indicating whenever the current logged file should be closed and a new one

started.

Configure maximum log retention time

retention : |str|, |int|, |timedelta| or |callable|_, optional

A directive filtering old files that should be removed during rotation or end of

program.

from loguru import logger

logger.add("test_loguru_{time}.log", rotation="1MB")   # The size of each file is 1MB. More than creating a new file

logger.add("test_loguru_{time}.log", rotation="12:00 ")   # Create a new file at 12:00 every day

logger.add("test_loguru_{time}.log", rotation="1 week")   # Create new files every week

(3) Support log time customization

from loguru import logger

logger.add("test_loguru_{time}.log", format="{time:YYYY-MM-DD A HH:mm:ss.SSSS} | {level} | {name} | {message}",level="DEBUG", rotation="500MB", retention="1 days")

logger.info("This is INFO")

(4) Support code exception tracking

backtrace (bool, optional) – Whether the exception trace formatted should be extended upward, beyond the catching point, to show the full stacktrace which generated the error.

diagnose (bool, optional) – Whether the exception trace should display the variables values to eases the debugging. This should be set to False in production to avoid leaking sensitive data.

1. Set in the add parameter

from loguru import logger

logger.add("test_loguru_{time}.log", format="{time} | {level} | {name} | {message}", level="DEBUG",
           rotation="1 KB", retention="10 seconds", encoding="utf-8", backtrace=True, diagnose=True)


def test(num_list):
    try:
        for num in num_list:
            logger.info(f"This Number is " + num)
    except Exception as e:
        logger.exception(e)


if __name__ == "__main__":
    l = [1, 2, 3]
    test(num_list=l)

  console output

Log file content

2. Direct Traceback recording using decorator

from loguru import logger

logger.add("test_loguru_{time}.log", format="{time} | {level} | {name} | {message}", level="DEBUG",
           rotation="1 KB", retention="10 seconds", encoding="utf-8")


@logger.catch
def test(num_list):
    for num in num_list:
        logger.info(f"This Number is " + num)


if __name__ == "__main__":
    l = [1, 2, 3]
    test(num_list=l)

console output

File output

So far, we can see that Loguru is very powerful, with simple application and intuitive debugging and tracking. Of course, it also has many powerful functions. You can go to the official website to learn

reference material:

github: https://github.com/Delgan/loguru

loguru help manual: https://loguru.readthedocs.io/en/stable/index.html

Posted by kellz on Thu, 18 Nov 2021 20:42:39 -0800