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

不言
不言Original
2018-09-15 13:53:052827browse

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')

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)  # 记录事件的日志

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()

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:
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