Article | carefree huan \

Source: Python Technology “ID: pythonall”

Over the years of writing Python, I have always used Python’s built-in logging module for logging. Each time, I have to write some configuration to output the log to a different location, set different log output formats, or split and compress the log, etc. There was nothing wrong with the journaling module until I stumbled upon a gadget that made journaling so easy! This artifact is loguru.

The installation

The installation of this library is very simple, using PIP directly. I use Python version 3 and the installation command is as follows:

pip3 install loguru
Copy the code

A profound

Once installed, we are ready to use it. The simplest way to use it is:


from loguru import logger

logger.debug('this is a debug message')
Copy the code

No configuration required, ready-to-use. In the preceding example, a debug log is generated. The output is as follows:


2021- 03- 16 22:17:23.640 | DEBUG    | __main__:<module>:8 - this is a debug message
Copy the code

The output log information contains the date, time, log level, number of code lines, and log content. You can also print warning, INFO, error, critical, success, and so on. The output logs are highlighted on the console and have different colors for each log level. Not cool!

The log file

Write files

In Loguru, an add() function is all you need to output a log file:


logger.add('hello.log')

logger.debug('i am in log file')
Copy the code

In the same directory, a log file hello.log is generated. If you open the log file, you can see the following:


2021- 03- 16 21:20:31.460 | DEBUG    | __main__:<module>:12 - i am in log file
Copy the code

Of course, we can add some parameters to specify the format and level of the log output in the file:


log = logger.add('world.log', format="{time} | {level} | {message}", level="INFO")

logger.debug('i am debug message')
logger.info('i am info message')
Copy the code

The corresponding file output is as follows:


2021- 03- 16T22:47:53.226998+0800 | INFO | i am info message
Copy the code

We set the file to record only info level information, so debug level logs are not written to the log file.

We can also add information to the log file name:


logger.add('hello_{time}.log')
Copy the code

When the above code runs, a log file with time is generated.

Stop writing files

When we no longer need to write the log to a file, we can always stop:


id = logger.add('world.log', format="{time} | {level} | {message}", level="INFO")
logger.info('this is a info message')
logger.remove(id)
logger.info('this is another info message')
Copy the code

The add() method returns the id of the log file. When we need to stop writing information, we use the remove() method, passing in the ID. After the above code runs, the log file records the following information:


2021- 03- 16T22:47:53.227389+0800 | INFO | this is a info message
Copy the code

After the remove() method is called, the subsequent log information is not written to the log file.

Scroll to log files

We can configure the rotation parameter to specify how the log file should be generated. Like normal logging, we can specify the generation strategy based on the file size, time, date, etc.

# more than200M generates a new file logger.add("size.log", rotation="200 MB") # Every day at noon12Click generate a new file logger.add("time.log", rotation="Twelve") # generate a new file logger.add("size.log", rotation="1 week")
Copy the code

Specifies the validity period of the log file

We can also specify log file retention by using the retention parameter:


logger.add("file.log", retention="30 days"Copy the code

Through the above configuration, you can specify that log files can be kept for a maximum of 30 days, and the log files that were saved earlier than 30 days will be deleted.

Configuring the Compressed File

To save space, there may be a need to compress log files, which Loguru can also do:


logger.add("file.log", compression="zip"Copy the code

From the above configuration, we specified that the log file should be compressed in zip format.

Exception handling

Loguru can not only log, but also catch exception information, which can help us better trace the cause of errors.

In the Loguru module, we usually have two ways of catching exceptions: through the catch decorator and through the Exception method.

The Catch decorator catches exceptions

Let’s look at an example:


@logger.catch
def a_function(x):
    return 1 / x

a_function(0)
Copy the code

The following information is displayed:

021- 03- 16 23:10:28.124 | ERROR    | __main__:<module>:32 - An error has been caught in function '<module>', process 'MainProcess' (25939), thread 'MainThread' (140735895298944):
Traceback (most recent call last):
  File "/ Users/cxhuan/Library/Application Support/JetBrains/IntelliJIdea2020.3 / plugins/python/helpers/pydev/pydevconsole py." ", line 483├ ─ 0├ ├, in <module> pydevconsole. Start_client (host, port)62146
    │            │            └ '127.0.0.1'├ ─ imp <function ├ ─ imp0x10fd596a8> └ < module'pydevconsole' from '/ Users/cxhuan/Library/Application Support/JetBrains IntelliJIdea2020.3 / plugins/python/helpers/p y... . > File "/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py", line 32, In 
      
        a_function(0) ├ 
       
         File "/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py", line 30, In a_function return 1 / x └ 0 ZeroDivisionError: Division by zero
       
      Copy the code

In the above code, I specially created a 1 divided by 0 exception, we can see the log output information is very detailed, will call each step of the error information is listed in detail, and also the parameter value is also printed out, there is a very intuitive directivity, it is abnormal analysis magic!

The exception method catches exceptions

Let’s go straight to the example:


def b_function1(x):
    try:
        return 1 / x
    except ZeroDivisionError:
        logger.exception("exception!!!")

b_function1(0)
Copy the code

Run the above code and the output is as follows:


2021- 03- 16 23:16:07.602 | ERROR    | __main__:b_function1:40 - exception!!!
Traceback (most recent call last):
  File "/ Users/cxhuan/Library/Application Support/JetBrains/IntelliJIdea2020.3 / plugins/python/helpers/pydev/pydevconsole py." ", line 483├ ─ 0├ ├, in <module> pydevconsole. Start_client (host, port)62254
    │            │            └ '127.0.0.1'├ ─ imp <function ├ ─ imp0x118d216a8> └ < module'pydevconsole' from '/ Users/cxhuan/Library/Application Support/JetBrains IntelliJIdea2020.3 / plugins/python/helpers/p y... File "/Users/cxhuan/Library/Application Support/JetBrains/IntelliJIdea2020.3 / plugins/python/helpers/pydev/pydevconsole py, line 411, "" In start_client process_exec_queue (interpreter) │ └ < _pydev_bundle. Pydev_ipython_console. InterpreterInterface object at 0x118d36240> └ 
      
       ...... File "/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py", line 42, In 
       
         b_function1(0) ├ 
        
          > File "/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py", line 38, In B_function1 return 1 / x ├ 0 ZeroDivisionError: Division by Zero
        
       
      Copy the code

Similarly, error details are printed in great detail and intuitively.

conclusion

Where there is a need, there is an implementation, but the one who can make the requirement so elegant and concise is the author of loguru. But also added a lot of very useful features, it is a ghost! If you found any of the artifacts you shared today useful, click “Watching” to support it!

PS: Reply “Python” within the public number to enter the Python novice learning exchange group, together with the 100-day plan!

Old rules, brothers still remember, the lower right corner of the “watching” click, if you feel the content of the article is good, remember to share moments to let more people know!

[Code access ****]

Identify the qr code at the end of the text, reply: 210317