Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python3 Loguru output log tool

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to use the Python3 Loguru output log tool", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Python3 Loguru output log tool how to use" article.

I. Preface

The Python logging module defines functions and classes that implement flexible event logging for applications and libraries.

In the process of program development, many programs have the need to record logs, and the logs contain information such as normal program access logs and possible errors, warnings and other information output. Python's logging module provides a standard log interface through which logs of various formats can be stored. Log recording provides a set of convenient functions for simple log recording usage.

The main benefit of using the Python Logging module is that all Python modules can participate in the logging Logging module provides a large number of flexible features.

Why use loguru?

It is simple and convenient to help us output the log information we need:

When you use Python to write programs or scripts, the problem you often encounter is the need to delete logs. On the one hand, it can help us to eliminate problems when there is something wrong with the program, and on the other hand, it can help us to record the information we need to pay attention to.

However, if we use our own logging module, we need to do different initialization and other related work. For students who are not familiar with the module, it is still a bit difficult, such as the need to configure Handler/Formatter and so on. As the complexity of the business increases, there are higher requirements for log collection, such as log classification, file storage, asynchronous writes, custom types, and so on.

Loguru is a simple and powerful third-party logging library for Python, which aims to reduce the pain of Python logging by adding a series of useful features to address the considerations of standard loggers.

Second, elegant use of loguru1. Install logurupip install loguru2. Introduction to functional features

There are many advantages, and here are some of the more important ones:

Right out of the box, no need to prepare

Import functions can be used without initialization

Easier file logging and rollover / retention / compression

More elegant string formatting output

Exceptions can be caught in a thread or main thread

You can set logging styles at different levels

Support for asynchronism and thread and multi-process security

Support for lazy computing

For scripts and libraries

Fully compatible with standard logging

Better date and time processing

3. Right out of the box, no need to prepare from loguru import logger logger.debug ("That's it, beautiful and simple logging!")

Import functions can be used without initialization, so you must ask, how to solve the problem?

How do I add a handler (handler)?

How to set the log format (logs formatting)?

How do you filter messages (filter messages)?

How do I set the log level?

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

Is it very easy~?

4. Easier file logging and rollover / retention / compression # log file recording logger.add ("file_ {time} .log") # log file dump logger.add ("file_ {time} .log", rotation= "500 MB") logger.add ("file_ {time} .log", rotation= "12:00") logger.add ("file_ {time} .log" Rotation= "1 week") # Clean logger.add ("file_X.log", retention= "10 days") # Save logger.add ("file_Y.log", compression= "zip") 5. More elegant string formatting output logger.info ("If you're using Python {}, prefer {feature} of course!", 3.10, feature= "f-strings") 6. Catch the exception @ logger.catch def my_function (x, y, z) in a child thread or main thread: # An error? It's caught anyway! Return 1 / (x + y + z) my_function (0,0,0) 7. You can set logging styles at different levels

Loguru automatically adds different colors for different log levels, and also supports custom colors.

Logger.add (sys.stdout, colorize=True, format= "{time} {message}") logger.add ('logs/z_ {time} .log', level='DEBUG', format=' {time:YYYY-MM-DD: mm:ss}-{level}-{file}-{line}-{message}', rotation= "10 MB") 8. Support for asynchronous and thread and multi-process security

By default, the log information added to logger is thread-safe. However, this is not multiprocess security, and we can ensure log integrity by adding enqueue parameters.

If we want to use logging in asynchronous tasks, we can use the same parameters to guarantee it. And wait for the execution to complete through complete ().

# write logger.add asynchronously ("some_file.log", enqueue=True)

You read it correctly. You only need enqueue=True to execute asynchronously.

9. Integrity description of the exception

A bug trace used to record exceptions that occur in code, and Loguru helps you identify problems by allowing the entire stack trace to be displayed, including variable values

Logger.add ("out.log", backtrace=True, diagnose=True) def func (a, b): return a / b def nested (c): try: func (5, c) except ZeroDivisionError: logger.exception ("when!") Nested (0) 10. Structured logging

The logs are serialized to make it easier to parse or pass data structures, using serialization parameters to convert each log message to an JSON string before sending it to the configured receiver.

At the same time, using the bind () method, you can put the logger message in context by modifying the additional record property. You can also have finer-grained control over logs by combining bind () and filter.

Finally, the patch () method allows dynamic values to be appended to the record dict of each new message.

# use of serializing into json format logger.add (custom_sink_function, serialize=True) # bind method logger.add ("file.log", format= "{extra [ip]} {extra [user]} {message}") context_logger = logger.bind (ip= "192.168.2.174") User= "someone") context_logger.info ("Contextualize your logger easily") context_logger.bind (user= "someone_else"). Info ("Inline binding of extra attribute") context_logger.info ("Use kwargs to add context during formatting: {user}", user= "anybody") # granularity controls logger.add ("special.log") Filter=lambda record: "special" in record ["extra"]) logger.debug ("This message is not logged to the file") logger.bind (special=True). Info ("This message, though, is logged to the file!") # patch () method logger.add (sys.stderr, format= "{extra [utc]} {message}") loggerlogger = logger.patch (lambda record: record ["extra"] .update (utc=datetime.utcnow ()) 11. Inert calculation

Sometimes you want to record details in a production environment without affecting performance, and you can use the opt () method to do this.

Logger.opt (lazy=True) .debug ("If sink level"

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report