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

Initial experience of logging in Python

編輯:Python

Preface

In the process of program development , Many programs need to log , And the information contained in the log has normal program access, and the log may have errors 、 Warning and other information output .

python default print Method to print the program log , However, it can not meet the requirements of log storage in our work 、 Show deeper needs .

This paper introduces a python Common log Libraries "logging", Next, let's see how to use it ~

logging Introduce

Python Of logging The module defines functions and classes that implement flexible event logging for applications and libraries .

Python Of logging The module provides a standard logging interface , It can store logs in various formats , Logging provides a set of convenience functions , For simple logging usage .

logging install

pip3 install logging

Easy to use

The code is as follows :

#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import logging
logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

By default ,logging The module prints the log to the screen (stdout), Log level is WARNING( That is, only the log level is higher than WARNING The log information will be output ), The log format is shown in the following figure :

The problem is coming. , What are the log levels and settings ?

How to set the log output method ? For example, output to the log file ?

Simple configuration

Simply configure the log level

  • DEBUG Details .
  • INFO Prove that things work as expected .
  • WARNING Indicates that something unexpected happened , Or there will be problems in the near future ( Such as ‘ The disk is full ’). The software is still working .
  • ERROR Because of more serious problems , The software can no longer perform some functions .
  • CRITICAL Serious mistakes , Indicates that the software can no longer run .
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import logging
# Simply configure the output mode and log level through the following methods
logging.basicConfig(filename='logger.log', level=logging.INFO)
logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

standard output ( The screen ) No information is displayed , It is found that... Has been generated under the current working directory logger.log, The contents are as follows :

Because by level=logging.INFO Set the log level to INFO, So all log information is output . Here comes the question .

What information can be configured through the above configuration methods ?

Logger,Handler,Formatter,Filter

Several important concepts

  • Logger Recorder , Exposed the interface that application code can use directly .
  • Handler processor , take ( The recorder produced ) Log records are sent to the appropriate destination .
  • Filter filter , Provides better granularity control , It can decide which logging to output .
  • Formatter formatter , Indicates the layout of the logging in the final output .

Logger Recorder

Logger It's a tree hierarchy , Using the interface debug,info,warn,error,critical You have to create Logger example , Create a recorder , If there is no explicit creation , By default, a root logger, And apply the default log level (WARN), processor Handler(StreamHandler, Print the log information on the standard output ), And formatter Formatter( The default format is the output format of the first simple use program ).

 Create method : logger = logging.getLogger(logger_name)
establish Logger After the instance , You can use the following methods to set the log level , Add processors Handler.
logger.setLevel(logging.ERROR) # Set the log level to ERROR, That is, only the log level is greater than or equal to ERROR The log will be output
logger.addHandler(handler_name) # by Logger Add a processor to the instance
logger.removeHandler(handler_name) # by Logger Instance to delete a processor

Handler processor

Handler There are many types of processors , There are three more commonly used ,StreamHandler,FileHandler,NullHandler, Details can be found at Python logging.handlers establish StreamHandler after , You can set the log level by using the following methods , Set the formatter Formatter, Add or remove filters Filter.

The code is as follows :

ch.setLevel(logging.WARN) # Specify the log level , lower than WARN Level logs will be ignored
ch.setFormatter(formatter_name) # Set up a formatter formatter
ch.addFilter(filter_name) # Add a filter , You can add more
ch.removeFilter(filter_name) # Delete a filter
StreamHandler
Create method : sh = logging.StreamHandler(stream=None)
FileHandler
Create method : fh = logging.FileHandler(filename, mode='a', encoding=None, delay=False)

Filter filter

Handlers and Loggers have access to Filters To complete more complex filtering than level .Filter Base classes only allow specific Logger Events below the hierarchy . For example ‘A.B’ The initialization of the Filter allow Logger ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ And so on ,logger‘A.BB’, ‘B.A.B’ You can't wait . If you initialize with an empty string , All events are accepted .

The code is as follows :

 Create method : filter = logging.Filter(name='')

The code is as follows :

# -*- encoding:utf-8 -*-
import logging
# create logger
logger_name = "example"
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
# create file handler
log_path = "./log.log"
fh = logging.FileHandler(log_path)
fh.setLevel(logging.WARN)
# create formatter
fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"
datefmt = "%a %d %b %Y %H:%M:%S"
formatter = logging.Formatter(fmt, datefmt)
# add handler and formatter to logger
fh.setFormatter(formatter)
logger.addHandler(fh)
# print log info
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

File configuration

The configuration file logging.conf as follows :

keys=root,example01
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[handlers]
keys=hand01,hand02
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('log.log', 'a')
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s

The code is as follows :

# -*- encoding:utf-8 -*-
import logging
import logging.config
logging.config.fileConfig("./logging.conf")
# create logger
logger_name = "example"
logger = logging.getLogger(logger_name)
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

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