Built-in module for getting started with Python--logging module

Keywords: Python encoding Unix

Built-in module for getting started with Python--logging module

1. logging -- log

(1) The role of logs:

<1>Log user information

<2>Record personal running water

<3>Record the running status of the software

<4>Record instructions from programmers

<5>For programmer code debugging

(2) Functional simple configuration of logs:

logging.debug() # debug debug 10

logging.info() # info information 20

logging.warning() # warning warning 30

logging.error() # error error 40

logging.critical() # critical hazard 50

(3) Information to be recorded in the log

By default, Python's logging module prints logs to standard output and displays only logs greater than or equal to the WARNING level, indicating that the default log level is set to WARNING

(log level level CRITICAL > ERROR > WARNING > INFO > DEBUG),

The default log format is log level: Logger name: User output message.

Logging starts with warning by default

logging.basicConfig(level = 30) #Tuning start level defaults to 30

(4) Manual gear

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="test.log",
                     filemode="a",
 )


 logging.debug("You're crazy,I am silly") # debug debugging
 logging.info("Go to my house in madness")   # info information
 logging.warning("Entangled to the end of the world")   # info warning
 logging.error("I can't get out of bed")           # Error error
 logging.critical("You can't go home")        # critical danger

<1> The logging module default behavior can be changed through specific parameters in the basicConfig() function, including:

  • filename: Creates a FiledHandler with the specified file name so that the log is stored in the specified file.
  • filemode: File opening method, which is used when filename is specified. The default value is "a" or "w".
  • Format: Specifies the log display format used by handler.
  • datefmt: Specifies the date time format.
  • Level: Set the level of logging
  • Stream: Creates a StreamHandler with the specified stream.You can specify an output to
  • sys.stderr,sys.stdout, or file (f=open('test.log','w')), defaults to sys.stderr.If both filename and stream parameters are listed, the stream parameter is ignored.

Formatting strings that may be used in the <2> format parameter:

  • (name)s Logger's name
  • (levelno)s Digital Log Level
  • (levelname)s Text Log Level
  • (pathname)s The full pathname of the module calling the log output function, which may not
  • File name of module where%(filename)s calls the log output function
  • Module name of log output function called by%(module)s
  • (funcName)s Calls the function name of the log output function
  • (lineno)d The line of code where the statement calling the log output function is located
  • %(created)f Current time, expressed in UNIX standard floating point numbers for time
  • Milliseconds since Logger creation when (relativeCreated)d outputs log information
  • (asctime)s The current time as a string.The default format is "2003-07-08 16:49:45,896".Milliseconds after comma
  • %(thread)d Thread ID.Maybe not
  • (threadName)s thread name.Maybe not
  • %(process)d process ID.Maybe not
  • %(message)s User Output Message

(5) Automatic stop

import logging
# Initialize an empty log
logger = logging.getLogger()   # --An object was created
# Create a file to log information
fh = logging.FileHandler('test.log',encoding='utf-8')
# Create a file to log information
fh1 = logging.FileHandler('test1.log',encoding='utf-8')
# Create something that can be output on the screen
ch = logging.StreamHandler()
# Define formats for information to be recorded
msg = logging.Formatter('%(asctime)s - [line:%(lineno)d] - %(filename)s - %(levelname)s - %(message)s')
# Define formats for information to be recorded
msg1 = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# Set Record Level
logger.setLevel(10) or logger.setLevel(logging.DEBUG)
# Hierarchical Correspondence Table
'''
DEBUG - 10
INFO - 20
WARNING - 30
ERROR - 40
CRITICAL - 50
'''
# Bind our format to the file
fh.setFormatter(msg)
fh1.setFormatter(msg)
# Bind our format to the screen
ch.setFormatter(msg1)
# Bind files that set store log information to logger logs
logger.addHandler(fh) #logger objects can add multiple fh and ch objects
logger.addHandler(fh1)
logger.addHandler(ch)
# Logging
logger.debug([1,2,3,4,])
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')

Posted by vincent30000 on Wed, 18 Sep 2019 18:42:05 -0700