Python uses logging to record logs

Python uses logging to record logs

The logging library adopts a modular design and provides many components: loggers Logger, processors Handler, filters Filterand formatters Formatter.

Filters are used to filter loggers and processors

  1. Logger exposes interfaces that can be directly used by application code

    1. Logger objects need to do three things.First, they expose many methods to the application code so that the application can log messages at runtime.Secondly, the logger object determines which ones by severity (default filtering facility) or filter object Log messages need to be recorded. Third, the logger object passes related log messages to all interested log processors. Commonly used methods of logger objects are divided into two categories: configuration and sending messages

    2. Logger.setLevel() specifies the lowest security level log information that the logger will process, debug is the lowest built-in security level, and critical is the highest built-in security level. For example, if the severity is INFO, the logger will only process INFO, WARNING, ERROR and CRITICAL messages, DEBUG messages will be ignored.

    3. Logger.addHandler() and Logger.removeHandler() add and remove handler objects from the logger object,

    4. Logger.addFilter() and Logger.removeFilter() add and remove filter objects from the logger object

  2. The Handler sends the log records (generated by the logger) to the appropriate destination: it can be a file, standard output, mail, or sent to any place via socket, http and other protocols


    [External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-gKnmhaQl-1605176592465)(C:\Users\93623\AppData\Roaming\Typora\typora-user-images\ image-20201105160053975.png)]

    1. The handler object is responsible for dispatching the appropriate log message (based on the severity of the log message) to the specified target of the handler. The Logger object can add zero or more handler objects through the addHandler() method. For example, an application can send All log messages are sent to the log file, all log messages of error level and above are sent to standard output, and all critical log messages are sent to an email address. In this example, three independent log messages are required. Each processor is responsible for sending messages of a specific level to a specific location.
    2. There are four common ones:
    3. logging.StreamHandler->Console output, constructor: StreamHandler([strm]), strm parameter is a file object, the default is sys.stderr
    4. logging.FileHandler->File output, constructor: FileHandler(filename[,mode]), filename is the file name, you must specify a file name, mode is the opening method of the file, the default is'a', that is, it is added to the end of the file.
    5. logging.handlers.RotatingFileHandler->Automatically divide the log file according to the size, once it reaches the specified size, regenerate the file, the constructor: RotatingFileHandler(filename[,mode[,maxBytes,[backupCount]]]), maxBytes is used to specify the log file The maximum file size, if maxBytes is 0, it means that the log file can be infinitely large, then the renaming process will not occur. backupCount is used to specify the number of backup files to be retained, for example, if you specify 2, when the renaming process When this happens, the original chat.log.2 will not be renamed, but deleted.
    6. logging.handlers.TimedRotatingFileHandler->Automatically split log files according to time, and automatically create new log files at certain intervals. Its constructor is:
      TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
      where the filename parameter It has the same meaning as the backupCount parameter and RotatingFileHandler.
      interval is the time interval.
      The when parameter is a string. Represents the unit of the time interval and is not case sensitive. It has the following values:
      S Seconds
      M Minutes
      H Hours
      D Days
      W Every week (interval==0 represents Monday)
      midnight Every morning
  3. Filter provides better granular control, it can decide which log records to output

  4. Formatter specifies the layout of the log records in the final output: the order, structure and content of the log information

    Formatting information that may be used in the ormat parameter:

    %(name)s Logger's name
    %(levelno)s Digital log level
    %(levelname)s Log level in text form
    %(pathname)s The full path name of the module that calls the log output function, it may not
    %(filename)s The file name of the module that calls the log output function
    %(module)s The name of the module that calls the log output function
    %(funcName)s The name of the function 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 the time in the 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". Milliseconds after the comma
    %(thread)d Thread ID. Maybe not
    %(threadName)s Thread name. Maybe not
    %(process)d Process ID. Maybe not
    %(message)s User output message
    1. The Formatter object sets the final rules, structure and content of the log information. The default time format is %Y-%m-%d %H:%M:%S

    2. Construction method:ft = logging.Formatter.__init_(fmt=None,datefmt=None,style='%')

warning debug will select warning

import logging

# 记录器
logger = logging.getLogger()
print(logger)
print(type(logger))
# # <RootLogger root (WARNING)>
# # <class 'logging.RootLogger'>
import logging
# 记录器
logger = logging.getLogger('applog')
print(logger)
print(type(logger))
# # <Logger applog (WARNING)>
# # <class 'logging.Logger'>
import logging
logger = logging.getLogger("applog")
logger.setLevel(logging.INFO)

consolehandler = logging.StreamHandler()
consolehandler.setLevel(logging.DEBUG)

filehandler = logging.FileHandler(filename="addlog.log")
filehandler.setLevel(logging.CRITICAL)

formatter = logging.Formatter("%(asctime)8s|%(levelname)8s|%(filename)s:%(lineno)s|%(message)s")
consolehandler.setFormatter(formatter)
filehandler.setFormatter(formatter)

logger.addHandler(consolehandler)
logger.addHandler(filehandler)

logger.debug('this is debug message')
logger.info('this is info message')
logger.warning('this is warning message')
logger.critical('this is critical message')
logger.warning('this is warning message')
logger.critical('this is critical message')

Guess you like

Origin blog.csdn.net/weixin_46129834/article/details/109650521