程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

New logging skills in Python

編輯:Python

Introduction Keep on learning , Continuous evolution ,get Log new skills

In general, we often use to record logs logging modular , We need to configure the template before using , Set up Handler、Formatter To preprocess , For example, log output location 、 Output format 、 Log blocking and backup . When using logs for different projects , It needs to be done in the early stage logger Configuration work , Compared to today get The new skills of the individual feel that the configuration is more 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:

1、 And logging difference , Why? loguru“ sweet ”

2、 install

3、 Quick to use

4、 Introduction to high-level usage

One 、 And logging difference , Why? loguru“ sweet ”

logging

loguru

identical

Provide simplicity 、 Flexible event recording function

Different

Explicit instantiation is required logger, And use Handler,Formatte,Filter

Reduce configuration steps ,add Functions rule all

Two 、 install

Old rules , The first step is to install the library , stay python3 In the environment , direct pip3 Can be installed

pip3 install loguru

3、 ... and 、 Quick to use

After successful installation , We can start

from loguru import logger
logger.debug("This is Debug")

There is no need for cumbersome configuration , Out of the box “ food ”,so easy

loguru The main object in is logger, Yes and only loguru, Why can I use it without configuration , That's because these configurations have been pre configured , Output format , Text color, etc , The console output is as follows :

The output includes time 、 Level 、 Module name 、 Line number and log information , In addition, its output is color , It looks more friendly (xuan) good (ku)

How about DIY Personalized customized logs , Let's look at the next chapter

Four 、 Introduction to high-level usage

Let's mainly look at loguru.logger Of “ universal ”add()

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

  You can see it in the source code ,add Many parameters , Such as level、format、filter、color wait , Let's focus on sink Parameters

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 file object

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

(3) It could be a logging Module Handler

(4) It can be a class or method

Let's try it

( One ) Save output log to file

from loguru import logger
logger.add("test_loguru_{time}.log") # stay add Define the file name of the output
logger.debug("This is Debug")

  Console output

Output the file to the current project directory

The contents of the document

( Two ) Support log size segmentation 、 Log retention time definitions

By log size 、 Time ( Hours 、 Zhou ) establish

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 the 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") # Size of each file 1MB. More than creating a new file
logger.add("test_loguru_{time}.log", rotation="12:00 ") # Every day 12 Click to create a new file
logger.add("test_loguru_{time}.log", rotation="1 week") # Create new files every week 

( 3、 ... and ) 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")

( Four ) 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、 stay 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、 Use the decorator directly Traceback Record

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

thus , We can see that Loguru It's powerful , Simple application , Debug trace is intuitive , 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 book :https://loguru.readthedocs.io/en/stable/index.html


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved