Python log processing module

Keywords: Python ascii

                       . Its main advantages are as follows:

  • 1. You can set different log levels to output only important information in the release version without displaying a large number of debugging information;
  • 2. Especially when the code runs on the server, when there is a problem, it can be analyzed by viewing the log.

Basic use of   logging module:

  • Set logger name

logger = logging.getLogger(log_name)

  • Set log level

logger.setLevel(logging.info)

  • Create a handler to write to the log file

fh = logging.FileHandler(log_file)

  • Set the log level, which is logging.WARNING by default

fh.setLevel(logLevel[log_level])

  • Define the output format of handler

formatter = logging.Formatter('%(asctime)s %(name)s [line:%(lineno)d] %(levelname)s %(message)s')

fh.setFormatter(formatter)

  • Add handler

logger.addHandler(fh)

  • format

%(levelno)s: print log level values

%(levelname)s: print log level name

%(pathname)s: print the path of the current executing program, which is actually sys.argv[0]

%(filename)s: print the current executing program name

%(funcName)s: current function for printing logs

%(lineno)d: print the current line number of the log

%(ASCII) s: time to print log

%(thread)d: print thread ID

%(threadName)s: print thread name

%(process)d: print process ID

%(message)s: print log information

The    example code is as follows:

import logging
import datetime
import os

# Define log level dictionary
logLevelDic={
    "info":logging.INFO,
    "debug":logging.DEBUG,
    "warning":logging.WARNING,
    "error":logging.ERROR
}

# Log save path
logSavePath=os.path.join(os.getcwd(),"logs")
if not os.path.exists(logSavePath):
    os.makedirs(logSavePath,exist_ok=True)
# current time 
curTime=datetime.datetime.now().strftime("%Y%m%d")
# Full name of the saved log
logFile=os.path.join(logSavePath,curTime+".SADCI.log")
# log level
logLevel="error"

class Logger:
    def __init__(self,logFile=logFile,logLevel=logLevelDic["error"]):
        self.logFile=logFile
        self.logLevel=logLevel
        # Set logger name
        self.logger=logging.getLogger()
        # Set parameter level
        self.logger.setLevel(self.logLevel)
        self.formatter=logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
        # Determine whether handlers exist
        if not self.logger.handlers:
            #  Write to console
            consoleStream=logging.StreamHandler()
            consoleStream.setLevel(self.logLevel)
            consoleStream.setFormatter(self.formatter)
            #  write file
            fileStream=logging.FileHandler(self.logFile,mode="a")
            fileStream.setLevel(self.logLevel)
            fileStream.setFormatter(self.formatter)
            self.logger.addHandler(consoleStream)
            self.logger.addHandler(fileStream)

def MyLogger():
    return Logger(logFile=logFile,logLevel=logLevelDic[logLevel]).logger


if __name__ == '__main__':
    MyLogger().error("test logg")

Posted by Mucello on Mon, 27 Apr 2020 09:29:23 -0700