Python3 common module --logging module

1. The logging module of python provides a standard log interface, through which logs in various formats can be stored. Log level: critical > error > warning > info > debug
By default, only logs with level greater than or equal to WARNING are displayed.


In the logging.basicConfig() function, you can change the default behavior of the logging module through specific parameters. The available parameters are filename: Create a FileHandler with the specified file name (the concept of handler will be explained in detail later), so that the log will be stored in the specified file. middle. filemode: The file opening mode. This parameter is used when filename is specified. The default value is "a" and can also be specified as "w". format: Specifies the log display format used by the handler. datefmt: Specifies the datetime format. level: Set the log level of the rootlogger (specific concepts will be explained later) Stream: Create a StreamHandler with the specified stream. You can specify output to sys.stderr, sys.stdout or a file, the default is sys.stderr. If both filename and stream parameters are listed, the stream parameter will be ignored.
Format strings that may be used in the format parameter: %(name)s Logger name%(levelno)s Digital log level%(levelname)s Text log level%(pathname)s The module that calls the log output function The full path name of the log output function, may not have it %(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, expressed as a floating point number representing time in UNIX standard %(relativeCreated)d When outputting log information, the number of milliseconds since the Logger was created %(asctime) s The current time as a string. The default format is "2003-07-08 16:49:45,896". After the comma is the millisecond %(thread)d thread ID. There may be no %(threadName)s thread names. There may be no %(process)d process ID. There may be no %(message)s user output messages

To have more flexible control over logging, you must understand the concepts of Logger, Handler, Formatter, and Filter:
logger provides an interface that applications can use directly;
The handler sends the log records (created by the logger) to the appropriate destination output;
filter provides a granularity device to decide which log records to output;
The formatter determines the final output format of the logging.
 
logger
Every program gets a Logger before outputting information. Logger usually corresponds to the module name of the program. For example, the graphical interface module of a chat tool can get its Logger like this:
LOG=logging.getLogger(”chat.gui”)
And the core module can be like this:
LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel): Specifies the minimum log level, levels lower than lel will be ignored. debug is the lowest built-in level, critical is the highest
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别
handler
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象

每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:
1) logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr

2) logging.FileHandler
和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。
3) logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。

4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。

看个例子:

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt=' %Y/%m/%d %H:%M:%S', filename='myapp.log', filemode='w')
logger = logging.getLogger(__name__)

def hello():
    print("hello world")

def main():
    logger.info("开始执行main函数")
    print("##"*10)
    hello()
    logger.info("调用hello() 函数")
    try:
        a = 2/0
        f = open("demon1.py", "r")
    except Exception as e:
        logger.error("除数不能为0")
    finally:
        logger.warning("文件没有正常关闭")

main()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324831059&siteId=291194637
Recommended