A brief introduction to Logging

Used for logging, there are six log levels by default (the values of the levels are in parentheses)

  1. NOTSET (0)
  2. The DEBUG (10)
  3. INFO (20)
  4. WARNING (30)
  5. ERROR (40)
  6. CRITICAL (50)

special

  • When you customize a log level, ensure that it is not the same as the default log level
  • Logging Outputs logs of a log level greater than or equal to the specified level. For example, if the log level is set to INFO, INFO, WARNING, ERROR, and CRITICAL logs are displayed.

 

Logging Common Objects

  • Logger: Logs that expose functions to applications that determine which logs are valid based on Logger and filter levels.
  • LogRecord: Logs are sent to the corresponding processor for processing.
  • Handler: The processor that sends log records (generated by loggers) to the appropriate destination.
  • Filter: Filters that provide better granular control over which log records to output.
  • Formatter: specifies the format of the log record in the final output.

 

Basic Logging Usage

Logging is very simple to use, using the basicConfig() method to meet basic usage needs; If the method takes no arguments, the Logger object is created according to the default configuration, and the default log level is set to WARNING. The optional parameters for this function are listed in the following table.

The parameter name Parameters to describe
filename Log output to the file name
filemode File mode, R [+], W [+], A [+]
format Format of the log output
datefat The format of the date and time attached to the log
style Format placeholders, default to “%” and “{}”
level Set the log output level
stream Defines an output stream that is used to initialize a StreamHandler object. The filename argument cannot be used together, otherwise ValueError will be raised
handles The Handler is used to create a Handler object. It cannot be used with the filename and stream arguments, otherwise ValueError will be raised

Logging code

1 logging.debug("debug")
2 logging.info("info")
3 logging.warning("warning")
4 logging.error("error")5 logging.critical("critical")
Copy the code

The test results

1 WARNING:root:warning
2 ERROR:root:error
3 CRITICAL:root:critical
Copy the code

However, when exceptions occur, the debug(), info(), warning(), error(), and critical() methods without parameters cannot record exception information. Exc_info =True is required. Or use the exception() method, or you can use the log() method, but also set the log level and exc_info parameters

1 a = 5 2 b = 0 3 try: 4 c = a / b 5 except Exception as e: 6 # Choose one of the following three ways, 7 Logging. exception(" exception occurred") 8 logging.error(" exception occurred", exc_info=True) 9 logging.log(level=logging.ERROR, msg="Exception occurred", exc_info=True)Copy the code

 

Logging Formatter object

The Formatter object is used to set the specific output format. Common formats are shown in the following table

format Variable description
%(asctime)s To construct the log time in a readable form, accurate to milliseconds by default, such as 2018-10-13 23:24:57,832, you can specify an additional datefmt parameter to specify the format of this variable
%(name) The name of the log object
%(filename)s The file name that does not contain the path
%(pathname)s The file name containing the path
%(funcName)s The name of the function where the log is recorded
%(levelname)s Log level name
%(message)s Specific log information
%(lineno)d Number of the line where logs are recorded
%(pathname)s The full path
%(process)d Current Process ID
%(processName)s Current process name
%(thread)d Current thread ID
%threadName)s Current thread name

 

Logging wrapper class

1 #! /usr/bin/env python 2 # -*- coding: Utf-8 -* -3 4 """ 5 __title__ = logging utility class 6 __Time__ = 2019/8/819:26 7 """ 8 import logging 9 from logging import handlers 10 11 12 class Loggers: 13 __instance = None 14 15 def __new__(cls, *args, **kwargs): 16 if not cls.__instance: 17 cls.__instance = object.__new__(cls, *args, **kwargs) 18 return cls.__instance 19 20 def __init__(self): Formater = logging.Formatter(23 '[%(asctime)s]-[%(LevelName)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] : %(message)s') 24 # Define a log collector 25 self.logger = logging.getLogger('log') 26 # Set the level 27 self.logger.setlevel (logging.debug) 28 # output channel a - file form 29 self. FileLogger = handlers. RotatingFileHandler (". / test. The log ", maxBytes = 5242880, BackupCount =3) 30 31 # Output channel 2 - console 32 self.console = logging.streamHandler () 33 # Console output level 34 Self. The console. SetLevel (logging. The DEBUG) 35 # output channel output format docking 36 self. The console. SetFormatter (formater) 37 Self. FileLogger. SetFormatter docking (formater) 38 # log collector output channel and the self. The logger. AddHandler (self. FileLogger) 40 self.logger.addHandler(self.console) 41 42 def debug(self, msg): 43 self.logger.debug(msg=msg) 44 45 def info(self, msg): 46 self.logger.info(msg=msg) 47 48 def warn(self, msg): 49 self.logger.warning(msg=msg) 50 51 def error(self, msg): 52 self.logger.error(msg=msg) 53 54 def excepiton(self, msg): 55 self.logger.exception(msg=msg) 56 57 58 loggers = Loggers() 59 60 if __name__ == '__main__': 61 loggers.debug('debug') 62 loggers.info('info')Copy the code
Copy the code

Logzero wrapper class

1 #! /usr/bin/env python 2 # -*- coding: Utf-8 -*- 3 4 """ 5 __title__ = logZero Log encapsulation class 6 __Time__ = 2019/8/819:267 "" 8 import logging 9 10 import logZero 11 from logzero import logger 12 13 14 class Logzero(object): 15 __instance = None 16 17 def __new__(cls, *args, **kwargs): 18 if not cls.__instance: 19 cls.__instance = object.__new__(cls, *args, **kwargs) 20 return cls.__instance 21 22 def __init__(self): 23 self.logger = logger 24 # console Input log format - with color 25 self.console_format = '%(color)s' \ 26 '(asctime) [% s] - (levelname) 1.1 [% s] - (filename) [% s] - [(lineno) (funcName) % s: % d] log information: %(message)s' \ 27 '%(end_color)s' 28 # create a Formatter object Logzero.logformatter (FMT =self.console_format) 30 # Supply the formatter argument to the setup_default_logger method 31 Logzero.setup_default_logger (formatter=self.formatter) 32 33 # Set log file output format 34 self.formater = logging.formatter (35 '(asctime) [% s] - [% s] (levelname) - (filename) [% s] - [(lineno) (funcName) % s: % d] log information: %(message)s') 36 # Set the log file level 37 logZero.loglevel (logging.debug) 38 # Print the log file path and format 39 logzero.logfile("F:\\imocInterface\\log/tests.log", formatter=self.formater) 40 41 def debug(self, msg): 42 self.logger.debug(msg=msg) 43 44 def info(self, msg): 45 self.logger.info(msg=msg) 46 47 def warning(self, msg): 48 self.logger.warning(msg=msg) 49 50 def error(self, msg): 51 self.logger.error(msg=msg) 52 53 def exception(self, msg): 54 self.logger.exception(msg=msg) 55 56 57 logzeros = Logzero() 58 59 if __name__ == '__main__': 60 logzeros.debug("debug") 61 logzeros.info("info") 62 logzeros.warning("warning") 63 logzeros.error("error") 64 a = 5 65 b = 0 66 try: 67 c = a / b 68 except Exception as e: 69 logzeros.exception("Exception occurred")Copy the code