Python log processing logging module

2020/04/27 10:00
Reading number 98
 

1、 Introduction and quick use of logging module

The logging module is a standard module built in Python. It is mainly used to output running logs. You can set the level of output logs, log saving path, log file rollback, etc.

advantage:

  1. You can set different log levels to output only important information in the release version without displaying a lot of debugging information;

  2. Especially when the code runs on the server, you can view the log for analysis when problems occur.

Logging for quick use

 # one Import Logging Package import logging  # two Set configuration information logging.basicConfig(level=logging. INFO,format= '%(asctime)s-%(name)s-%(levelname)s-%(message)s'  # three Define the log name getlogger logger = logging.getLogger( "log_demo"  # four info,debug logger.info( "info"  logger.debug( "debug"  logger.warning( "warning" 


 

2、 Basic usage of the logging module

Log output file

  • Set the logger name

    logger = logging.getLogger(log_name)

  • Set log level

    logger.setLevel(logging.info)

  • Create a handler for writing log files

    fh = logging.FileHandler(log_file)

  • Set the log level. The default is logging WARNING

    fh.setLevel(logLevel[log_level])

  • Define the output format of the 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 execution program, which is actually sys. argv [0]

    %(filename) s: Print the name of the current executing program

    %(funcName) s: Current function for printing logs

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

    %(asctime) s: Time of printing log

    %(thread) d: Print thread ID

    %(threadName) s: Print thread name

    %(process) d: Print process ID

    %(message)s Print log information

  • code

 import logging  # one Set the logger name logger = logging.getLogger( "log_file_demo"  # two Set log level logger. setLevel (logging. INFO) # three Create handler fh_stream = logging. StreamHandler()  #Write File fh_file = logging. FileHandler( "./test.log"  # four Set Log Level fh_stream.setLevel(logging. DEBUG)  fh_file.setLevel(logging. WARNING)  # five Define Output Format formatter = logging. Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s '  fh_stream.setFormatter(formatter)  fh_file.setFormatter(formatter)  # six Add handler logger.addHandler(fh_stream)  logger.addHandler(fh_file)  # seven Operation output logger.info( "This is a info"  logger.debug( "This is a debug"  logger.warning( "This is a warning" 
 

3、 Encapsulate logs

 import logging  from config import Conf  import datetime,os  from config.Conf import ConfigYaml  #Define log level mapping log_l = {              "info" : logging. INFO,                "debug" : logging. DEBUG,                "warning" : logging. WARNING,        "error" : logging. ERROR } # one . Create Class class   Logger  #2. Define parameters #Output file name, Loggername, log level      def __init__(self, log_file,log_name,log_level): Self. log_file=log_file # extension profile Self. log_name=log_name # parameter Self. log_level=log_level # Profile # three . Write output console or file #Set the logger name          self.logger = logging.getLogger(self.log_name)              #Set log level          self.logger.setLevel(log_l[self.log_level]) #logging. INFO              #Determine whether the handlers exist           if  not self.logger.handlers:                      #Output Console              fh_stream = logging. StreamHandler()                                    fh_stream.setLevel(log_l[self.log_level])                                    formatter = logging. Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s ' )                fh_stream.setFormatter(formatter)                      #Write File              fh_file = logging. FileHandler(self.log_file)                                    fh_file.setLevel(log_l[self.log_level])                                    fh_file.setFormatter(formatter)                      #Add handler              self.logger.addHandler(fh_stream)                                    self.logger.addHandler(fh_file)  # four . Initialization parameter data #Log file name, log file level #Log file name=logs directory+current time+extension #Log directory log_path = Conf.get_log_path()  #Current time current_time = datetime.datetime.now().strftime( "%Y-%m-%d"  #Extension log_extension = ConfigYaml().get_conf_log_extension()  logfile = os.path.join(log_path,current_time+log_extension)  #print(logfile)  #Log file level loglevel = ConfigYaml().get_conf_log()  #print(loglevel)  # five . External method, initial log tool class, for other classes def my_log(log_name = __file__):               return  Logger(log_file=logfile,log_name=log_name,log_level=loglevel).logger         
if  __name__ ==  "__main__" :               my_log().debug( "This is a debug" )     



This article is shared from the WeChat official account Sogou QA.
In case of infringement, please contact support@oschina.cn Delete.
Participation in this article“ OSC Source Innovation Plan ”, welcome you to join us and share with us.

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
zero Collection
zero fabulous
 Back to top
Top