SoFunction
Updated on 2024-10-29

Python logging logging library example details

Simple use of logging

Used for logging, with six logging levels by default (values corresponding to the levels are in parentheses)

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

special

  • When customizing the log level, be careful not to use the same value as the default log level.
  • logging outputs log messages at a level greater than or equal to the set logging level. For example, if the set logging level is INFO, logs at the INFO, WARNING, ERROR, and CRITICAL levels will be output.

|2logging common objects

  • Logger: logging, exposing functions to the application, deciding which logs are valid based on the logger and filter level.
  • LogRecord : logger , the log will be passed to the appropriate processor processing .
  • Handler : Handler that sends the log records (generated by the logger) to the appropriate destination.
  • Filter : Filter, provides better granularity control, it can decide which log records to output.
  • Formatter: Formatter, specifies the format of the log records in the final output.

|3logging basic use

Logging is very simple to use, using thebasicConfig() method is sufficient for basic use; if the method is not passed parameters, the Logger object is created according to the default configuration, and the default logging level is set to WARNING, the optional parameters of the function are shown in the following table.

Parameter name

Parameter Description

filename

Filename of the file to which the log is output

filemode

File mode, r[+], w[+], a[+]

format

Format of log output

datefat

Format of the log with date and time

style

Format placeholders, defaults to "%" and "{}".

level

Setting the log output level

stream

Define the output stream, used to initialize the StreamHandler object, can't use the filename parameter together, otherwise it will be ValueError exception.

handles

Define the handler, used to create the Handler object, can not be used together with filename, stream parameters, otherwise it will also throw a ValueError exception

Logging Code

 ("debug")
 ("info")
 ("warning")
 ("error")5 ("critical")

Test results

WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical

However, when an exception occurs, using the debug(), info(), warning(), error(), and critical() methods without parameters will not log the exception information, and you need to set exc_info=True, or use the exception() method, or use the log() method, but you also need to set the Log level and exc_info parameter

a = 5
 b = 0
 try:
 c = a / b
 except Exception as e:
 # One of the following three options, the first is recommended
 ("Exception occurred")
 ("Exception occurred", exc_info=True)
 (level=, msg="Exception occurred", exc_info=True)

|4logging of Formatter object

The Formatter object is used to set the specific output format, and the commonly used formats are shown in the table below.

specification

Variable Description

%(asctime)s

Constructs the time of the log into a readable form, by default to milliseconds, e.g., 2018-10-13 23:24:57,832, and you can additionally specify the datefmt parameter to specify the format of this variable

%(name)

Name of the log object

%(filename)s

File names without paths

%(pathname)s

File name with path

%(funcName)s

The name of the function where the log records are located

%(levelname)s

Level name of the log

%(message)s

Specific log messages

%(lineno)d

The line number where the log record is located

%(pathname)s

full path

%(process)d

Current process ID

%(processName)s

Current process name

%(thread)d

Current thread ID

%threadName)s

Current thread name

|5logging wrapper class

 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 """
 __title__ = loggingtools
 __Time__ = 2019/8/8 19:26
 """
 import logging
 from logging import handlers
 class Loggers:
  __instance = None
  def __new__(cls, *args, **kwargs):
   if not cls.__instance:
    cls.__instance = object.__new__(cls, *args, **kwargs)
   return cls.__instance
  def __init__(self):
   # Set the output format
   formater = (
    '[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] : %(message)s')
   # Define a log collector
    = ('log')
   # Setting level
   ()
   # Output channel one - in document form
    = ("./", maxBytes=5242880, backupCount=3)
   # Output Channel Two - Console
    = ()
   # Console output level
   ()
   # Output Channel Docking Output Format
   (formater)
   (formater)
   # Log Collector Docking Output Channels
   ()
   ()
  def debug(self, msg):
   (msg=msg)
  def info(self, msg):
   (msg=msg)
  def warn(self, msg):
   (msg=msg)
  def error(self, msg):
   (msg=msg)
  def excepiton(self, msg):
   (msg=msg)
 loggers = Loggers()
 if __name__ == '__main__':
  ('debug')
  ('info')

|6logzero wrapper class

 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 """
 __title__ = logzerolog wrapper class
 __Time__ = 2019/8/8 19:26
 """
 import logging
 import logzero
 from logzero import logger
 class Logzero(object):
  __instance = None
  def __new__(cls, *args, **kwargs):
   if not cls.__instance:
    cls.__instance = object.__new__(cls, *args, **kwargs)
   return cls.__instance
  def __init__(self):
    = logger
   # console console input log format - with colors
   self.console_format = '%(color)s' \
        '[%(asctime)s]-[%(levelname)1.1s]-[%(filename)s]-[%(funcName)s:%(lineno)d] Log messages: %(message)s ' \
        '%(end_color)s '
   # Create a Formatter object
    = (fmt=self.console_format)
   # Provide the formatter to the formatter parameter of the setup_default_logger method
   logzero.setup_default_logger(formatter=)
   # Set the log file output format
    = (
    '[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] Log messages: %(message)s')
   # Set the log file level
   ()
   # Output log file path and format
   ("F:\\imocInterface\\log/", formatter=)
  def debug(self, msg):
   (msg=msg)
  def info(self, msg):
   (msg=msg)
  def warning(self, msg):
   (msg=msg)
  def error(self, msg):
   (msg=msg)
  def exception(self, msg):
   (msg=msg)
 logzeros = Logzero()
 if __name__ == '__main__':
  ("debug")
  ("info")
  ("warning")
  ("error")
  a = 5
  b = 0
  try:
   c = a / b
  except Exception as e:
   ("Exception occurred")

summarize

The above is a small introduction to the logging log library in Python examples in detail, I hope to help you, and thank you very much for your support of my website!