Examples of logging usage in the Python standard library

WBOY
Release: 2022-09-05 17:42:31
forward
1777 people have browsed it

[Related recommendations: Python3 video tutorial]

1. Introduction to logging

logging is a commonly used logging library in the Python standard library. Logs in various formats are stored through the logging module. It is mainly used to output running logs. You can set the output log level, log saving path, log file rollback, etc.

2. Simple usage example

First create a logger.py file, the code in it is as follows:

import logging
 
# 1.创建一个logger实例,并且logger实例的名称命名为“single info”,设定的严重级别为DEBUG
LOGGER = logging.getLogger('single info')
LOGGER.setLevel(logging.DEBUG)
 
# 2.创建一个handler,这个主要用于控制台输出日志,并且设定严重级别
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
 
# 3.创建handler的输出格式(formatter)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
# 4.将formatter添加到handler中
ch.setFormatter(formatter)
 
# 5.将handler添加到logger中
LOGGER.addHandler(ch)
Copy after login

After working with logger Create a demo.py file in the same directory of the .py file, and reference the previously created logger instance in the demo.py file. The code is as follows:

from logger import LOGGER
 
LOGGER.debug("打印DEBUG级别的日志")
LOGGER.info("打印INFO级别的日志")
Copy after login

Execute the demo.py file, and the input content in the console is as follows:

2022-09-03 17:38:16,554 - single info - DEBUG - Print DEBUG level logs
2022-09-03 17:38:16,555 - single info - INFO - Print INFO level log

3, log level

Default In this case, the log level of logging is WARNING, and the log is printed to the console. The log level size relationship is: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

import logging
 
LOGGER = logging.getLogger('single info')
 
LOGGER.error("打印ERROR级别日志")
LOGGER.warning("打印WARNING级别日志")
LOGGER.info("打印INFO级别日志")
Copy after login

Execute the above code, the output content is:

Print ERROR level log
Print WARNING level log

You can see that since the log level of INFO is less than WARNING, the corresponding log is not output

4. Various parameters of printing format

%(asctime)s: Create human readable format when logging Time, by default is in the form of '2022-09-03 17:28:38,073' (the number after the comma is the millisecond part of the time)

%(name)s : Indicates the name of the logger instance

%(levelname)s: The log level of the printed log

%(message)s: Indicates the content of the log

5. Output the log to the specified file

Place the above logger.py The file is modified as follows:

import logging
 
# 1、创建一个logger实例,并且logger实例的名称命名为“single info”,设定的严重级别为DEBUG
LOGGER = logging.getLogger('single info')
LOGGER.setLevel(logging.DEBUG)
 
# 2、创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',encoding="utf-8", mode="a")
fh.setLevel(logging.WARNING)
 
#3、定义handler的输出格式(formatter)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(lineno)d : %(message)s')
 
# 4、给handler添加formatter
fh.setFormatter(formatter)
 
# 5、给logger添加handler
LOGGER.addHandler(fh)
Copy after login

The code in the demo.py file is:

from logger import LOGGER
 
LOGGER.debug("打印DEBUG级别的日志")
LOGGER.error("打印ERROR级别的日志")
Copy after login

Execute the demo.py file, we will see that a name will be generated under the root directory of the project is the test.log file, and the content in the file is:

Print ERROR level log
Print WARNING level log

Special tip: Due to To output Chinese in the log file, you need to set the encoding when specifying the log file

6. Log rollback (rolling according to the file size)

Only modify the logger.py file: define a RotatingFileHandler, back up up to 3 log files, each log file can be up to 1K

import logging
from logging.handlers import RotatingFileHandler
 
# 1、创建一个logger实例,并且logger实例的名称命名为“single info”,设定的严重级别为DEBUG
LOGGER = logging.getLogger('single info')
LOGGER.setLevel(logging.DEBUG)
 
# 2、定义一个RotatingFileHandler,最多备份3个日志文件,每个日志文件最大1K
rHandler = RotatingFileHandler("log.txt",maxBytes = 1,backupCount = 3,encoding="utf-8", mode="a")
rHandler.setLevel(logging.WARNING)
 
#3、定义handler的输出格式(formatter)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(lineno)d : %(message)s')
 
# 4、给handler添加formatter
rHandler.setFormatter(formatter)
 
# 5、给logger添加handler
LOGGER.addHandler(rHandler)
Copy after login

After running demo.py multiple times, you can see that there will be new files under the root directory of the project Add four files:

log.txt represents the file stored in the current log, log.txt.1, log.txt.2 and log.txt.3 represent Is a log backup file.

7. Log rollback (rolling according to time)

Only modify the logger.py file: define a TimedRotatingFileHandler, back up up to 3 log files, every 5 seconds As an interval point of a log file

import logging
from logging.handlers import TimedRotatingFileHandler
from statistics import mode
 
# 1、创建一个logger实例,并且logger实例的名称命名为“single info”,设定的严重级别为DEBUG
LOGGER = logging.getLogger('single info')
LOGGER.setLevel(logging.DEBUG)
 
# 2、定义一个TimedRotatingFileHandler,最多备份3个日志文件,每隔5秒作为一个日志文件的间隔点
rHandler =TimedRotatingFileHandler(filename="ds_update", when="S", interval=5, backupCount=3,encoding="UTF-8")
rHandler.setLevel(logging.WARNING)
 
# 3、定义handler的输出格式(formatter)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(lineno)d : %(message)s')
 
# 4、给handler添加formatter
rHandler.setFormatter(formatter)
 
# 5、给logger添加handler
LOGGER.addHandler(rHandler)
Copy after login

After running demo.py multiple times, you can see that four new files will be added under the root directory of the project:

ds_update represents the file stored in the current log, ds_update.2022-09-03_19-24-50, ds_update.2022-09-03_19-24-45 and ds_update.2022-09-03_19-24-36 represent Log backup files, log backup files are rolled from recent to far in chronological order.

【Related recommendations: Python3 video tutorial

The above is the detailed content of Examples of logging usage in the Python standard library. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template