Home Backend Development Python Tutorial What is the use of the logging module in python? Introduction to the usage of logging module

What is the use of the logging module in python? Introduction to the usage of logging module

Sep 15, 2018 pm 01:53 PM
logging module

This article brings you what is the use of the logging module in python? The usage introduction of the logging module has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The logging module is a built-in module that comes with pyhton, providing a standard logging interface

Log level list

logger: generate logs Object
Filter: object for filtering logs
Handler: receives logs and controls printing to different places. FileHandler is used to print to files, StreamHandler is used to print to terminals
Formatter: different logs can be customized format object, and then bind it to different Handler objects to control the log formats of different Handlers

Code examples of how to use several objects:

'''critical=50
error =40
warning =30
info = 20
debug =10'''
 
 import logging 
#1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出logger=logging.getLogger(__file__) 
#2、Filter对象:不常用,略
 #3、Handler对象:接收logger传来的日志,然后控制输出h1=logging.FileHandler('t1.log') #打印到文件h2=logging.FileHandler('t2.log') #打印到文件h3=logging.StreamHandler() #打印到终端
 #4、Formatter对象:日志格式formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)
 
formmater2=logging.Formatter('%(asctime)s :  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)
 
formmater3=logging.Formatter('%(name)s %(message)s',) 
 
#5、为Handler对象绑定格式h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
h3.setFormatter(formmater3) 
#6、将Handler添加给logger并设置日志级别logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(h3)
logger.setLevel(10) 
#7、测试logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')
Copy after login

Note: The log will be The logger first filters once and then to the Handler object. When the Handler object and the logger object set the log level at the same time, the final log level will be set according to the highest level of the two.

Can be used in the logging.basicConfig() function The default behavior of the logging module can be changed through specific parameters. The available parameters are
filename: Create a FiledHandler with the specified file name, so that the log will be stored in the specified file
filemode: The file opening method, when filename is specified When using this parameter, the default value is "a" and can also be specified as "w".
format: Specify the log display format used by the handler
datefmt: Specify the date and time format
level: Set the log level of the rootlogger
stream: Create a StreamHandler with the specified stream. You can specify the output to sys.stderr, sys.stdout or a file. The default is sys.stderr. If both filename and stream parameters are listed at the same time, the stream parameter will be ignored.

Format string that may be used in the format parameter:

%(name)s Logger’s name

%(levelno)s The log level in numerical form

%(levelname)s The log level in text form

%(pathname)s The completeness of the module that calls the log output function Path name, may not have

%(filename)s The file name of the module that calls the log output function

%(module)s The module name that calls the log output function

% (funcName)s The function name that calls the log output function

%(lineno)d The line of code where the statement that calls the log output function is located

%(created)f The current time, in UNIX standard A floating point number representing time.

%(relativeCreated)d The number of milliseconds since the Logger was created when outputting log information.

%(asctime)s The current time in string form. The default format is "2003-07-08 16:49:45,896". What follows the comma is the thread ID in milliseconds

%(thread)d. There may be no

%(threadName)s thread names. There may be no

%(process)d process ID. There may not be messages output by

%(message)s users

Attached is a directly usable log template:

"""
logging配置
"""
 
import os
import logging.config
 
# 定义三种日志输出格式 开始
 
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字
 
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
 
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
 
# 定义日志输出格式 结束
 
logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录
 
logfile_name = 'all2.log'  # log文件名
 
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)
 
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)
 
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        # 这里的logger对象名字为''是为了getLogger()获取不同的日志对象时能获取相同的配置,当想要让不同的日志对象有不同的配
# 置时,可在这里添加logger对象
        # 当getLogger()获取的logger对象名称不存在时,如果存在key=''的配置,则使用默认key=''的配置
        '': {
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}
 
 
def load_my_logging_cfg(event_log):
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
#    logger = logging.getLogger(__name__)  # 生成一个log实例
#    logger.info(event_log)  # 记录事件的日志
Copy after login

Test:

"""
MyLogging Test
"""
import time
import logging
import my_logging  # 导入自定义的logging配置
logger = logging.getLogger(__name__)  # 生成logger实例
def demo():
    logger.debug("start range... time:{}".format(time.time()))
    logger.info("中文测试开始。。。")
    for i in range(10):
        logger.debug("i:{}".format(i))
        time.sleep(0.2)
    else:
        logger.debug("over range... time:{}".format(time.time()))
    logger.info("中文测试结束。。。")
if __name__ == "__main__":
    my_logging.load_my_logging_cfg()  # 在你程序文件的入口加载自定义logging配置
    demo()
Copy after login

Related recommendations :

Use the logging module in Python instead of print (a concise guide to logging)

Usage examples of the logging module in Python

The above is the detailed content of What is the use of the logging module in python? Introduction to the usage of logging module. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles