Python's third-party library-logging library learning

Python's third-party library-logging library learning

logging.debug()
logging.info()
logging.warning()
logging.error()
logging.critical()
Filters are covered in more detail in Filter Objects.
Filters are covered in more detail in Filter Objects.

1. Save to a file

logging.basicConfig(filename=‘example.log’, encoding=‘utf-8’, level=logging.DEBUG)

(Changed in version 3.9: The encoding argument was added.
In earlier Python versions, or if not specified, the encoding used was the default used by open().
Although not shown in the example above, one can now also be passed The error parameter, which determines how encoding errors are handled.
See the documentation for open() for available values ​​and defaults.)

logging.basicConfig(filename=‘example.log’, filemode=‘w’, level=logging.DEBUG)

It is used to handle whether the additional content is to overwrite the original content or append to the original content. The default is to append to the original content, filemode='w' means directly overwrite the original content

# 用于在日志中输出中文
import logging
logger=logging.getLogger()
fh=logging.FileHandler("D:\\ZhiPuAI\\article_match\\match.log",encoding="utf-8",mode="w")
logger.addHandler(fh)
logger.setLevel(logging.INFO)

2. Output variable information

logging.warning(‘%s before you %s’, ‘Look’, ‘leap!’)
logging.basicConfig(format=‘%(levelname)s:%(message)s’, level=logging.DEBUG)

The output is:
DEBUG:This message should appear on the console

logging.basicConfig(format=‘%(asctime)s %(message)s’)

The output is:
2010-12-12 11:41:42,612 is when this event was logged.

logging.basicConfig(format=‘%(asctime)s %(message)s’, datefmt=‘%m/%d/%Y %I:%M:%S %p’)

The output is:
12/12/2010 11:46:36 AM is when this event was logged.

3. Formatter format

insert image description here

# 设置输出的格式
LOG_FORMAT = "时间:%(asctime)s - 日志等级:%(levelname)s - 日志信息:%(message)s"
# 对logger进行配置——日志等级&输出格式
logging.basicConfig(level=logging.WARNING, format=LOG_FORMAT)
注意:logging.basicConfig()只能有一个哦!如果写多条——只有第一条会生效!!!

insert image description here

4. Flexible component format

insert image description here
insert image description here
insert image description here

import logging

# 创建一个logger(日志记录器)对象;
my_logger = logging.Logger("first_logger")


# 第一个日志处理器
my_handler = logging.FileHandler('test.log')

my_handler.setLevel(logging.INFO)
my_format = logging.Formatter("时间:%(asctime)s 日志信息:%(message)s 行号:%(lineno)d")

my_handler.setFormatter(my_format)
my_logger.addHandler(my_handler)


# 第二个日志处理器
you_handler = logging.StreamHandler()

you_handler.setLevel(logging.DEBUG)
you_format = logging.Formatter("时间:%(asctime)s 日志信息:%(message)s 行号:%(lineno)d 这是StreamHandler")

you_handler.setFormatter(you_format)
my_logger.addHandler(you_handler)


# 使用:
my_logger.info("我是日志组件")

おすすめ

転載: blog.csdn.net/baidu_41810561/article/details/122114060