python log

Posted by frist44 on Mon, 17 Jan 2022 12:02:57 +0100

The purpose of recording program log information is to:

  1. It is very convenient to understand the operation of the program
  2. It can analyze the user's operation behavior, preferences and other information
  3. It is convenient for developers to check bug s

2. Introduction to logging level

The logs can be divided into 5 levels, from low to high:

  1. DEBUG
  2. INFO
  3. WARNING
  4. ERROR
  5. CRITICAL

Log level description:

  • DEBUG: used when debugging a bug
  • INFO: used when the program is running normally
  • WARNING: the program is not used as expected, but it is not an error, such as user login password error
  • ERROR: used when the program has an ERROR, such as IO operation failure
  • CRITICAL: a particularly serious problem that causes the program to no longer run. For example, the disk space is empty and is rarely used
  • The default is WARNING level. Log information is recorded only when the level is above or above WARNING.
  • The order of log level from low to high is: debug < info < warning < error < critical

3. Use of logging

There are two ways to record logs in the logging package:

  1. Output to console
  2. Save to log file

Example code for outputting log information to the console:

import logging

logging.debug('This is a debug Level log information')
logging.info('This is a info Level log information')
logging.warning('This is a warning Level log information')
logging.error('This is a error Level log information')
logging.critical('This is a critical Level log information')

Operation results:

WARNING:root:This is a warning Level log information
ERROR:root:This is a error Level log information
CRITICAL:root:This is a critical Level log information

explain:

  • The log information only displays logs with a WARNING level greater than or equal to, which indicates that the default log level is set to WARNING

logging log level and output format settings:

import logging

# Set log level and output log format
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

logging.debug('This is a debug Level log information')
logging.info('This is a info Level log information')
logging.warning('This is a warning Level log information')
logging.error('This is a error Level log information')
logging.critical('This is a critical Level log information')

Operation results:

2019-02-13 20:41:33,080 - hello.py[line:6] - DEBUG: This is a debug Level log information
2019-02-13 20:41:33,080 - hello.py[line:7] - INFO: This is a info Level log information
2019-02-13 20:41:33,080 - hello.py[line:8] - WARNING: This is a warning Level log information
2019-02-13 20:41:33,080 - hello.py[line:9] - ERROR: This is a error Level log information
2019-02-13 20:41:33,080 - hello.py[line:10] - CRITICAL: This is a critical Level log information

Code Description:

  • Level indicates the set log level
  • Format indicates the output format of the log. Parameter Description:
    • %(levelname)s: print log level name
    • %(filename)s: print the name of the current executing program
    • %(lineno)d: the current line number of the print log
    • %(actime) s: time to print the log
    • %(message)s: print log information

Example code of saving log information to log file:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    filename="log.txt",
                    filemode="w")

logging.debug('This is a debug Level log information')
logging.info('This is a info Level log information')
logging.warning('This is a warning Level log information')
logging.error('This is a error Level log information')
logging.critical('This is a critical Level log information')

The log will be automatically generated in this directory Txt file to generate log data

Operation results:

2022-01-15 11:31:14,529 - web.py[line:59] - INFO: dynamic resource request: / index html
 2022-01-15 11:31:22,542 - web.py[line:63] - INFO: static resource request: / df
 2022-01-15 11:46:14,034 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:46:14,036 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:47:24,065 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:47:26,655 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:47:45,224 - web.py[line:75] - INFO: static resource request: / favicon ico
 2022-01-15 11:52:15,723 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:52:23,513 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:52:31,315 - web.py[line:60] - INFO: dynamic resource request: / index html
 2022-01-15 11:52:36,838 - web.py[line:75] - INFO: static resource request: / favicon ico

4. Application of logging in mini web project

web. Example of logging used by py program:

  1. The program entry module sets the logging settings

     import socket
     import threading
     import sys
     import framework
     import logging
    
     # logging log configuration
     logging.basicConfig(level=logging.DEBUG,
                         format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                         filename="log.txt",
                         filemode="w")
    
  2. INFO level log output, example code:

     # Determine whether it is a dynamic resource request
     if request_path.endswith(".html"):
         """Here is the dynamic resource request. The request information is handed over to the framework for processing"""
         logging.info("Dynamic resource request:" + request_path)
         ...
     else:
         """Here is the static resource request"""
         logging.info("Static resource request:" + request_path)
         ...
    
  3. WARNING level log output, example code:

     # Get command line parameter judgment length
     if len(sys.argv) != 2:
         print("Execute the following command: python3 xxx.py 9000")
         logging.warning("The user started the program on the command line. The number of parameters is incorrect!")
         return
    
     # Determine whether the port number is a number
     if not sys.argv[1].isdigit():
         print("Execute the following command: python3 xxx.py 9000")
         logging.warning("The user started the program on the command line. The argument is not a numeric string!")
         return
    

framework. Example of logging used by py program:

  1. ERROR level log output, example code:

     # Processing dynamic resource requests
     def handle_request(env):
         # Get dynamic request resource path
         request_path = env["request_path"]
         print("Dynamic resource request received:", request_path)
         # Traverse the routing list and select the function to execute
         for path, func in route_list:
             if request_path == path:
                 result = func()
                 return result
         else:
             logging.error("The corresponding route is not set:" + request_path)
             # Dynamic resource not found
             result = not_found()
             return result
    

explain:

  • The logging configuration information is set once in the program entry module, and the whole program can take effect.
    • logging.basicConfig indicates logging configuration operation

5. Summary

  • The logging package is used to record the log information in the python program
  • There are five logging levels:

    1. DEBUG
    2. INFO
    3. WARNING
    4. ERROR
    5. CRITICAL
  • There are 5 functions to print (record) logs:

    1. logging. The DEBUG function means to print (record) DEBUG level log information
    2. logging.info function, which means to print (record) log information at INFO level
    3. logging. The WARNING function means to print (record) the WARNING level log information
    4. logging. The ERROR function means to print (record) the log information at the ERROR level
    5. logging.critical function, which means to print (record) CRITICAL level log information

Topics: Python Back-end