An example of a python logging class library

  • 2020-04-02 14:23:53
  • OfStack

One, simple use


def TestLogBasic():
    import logging
    logging.basicConfig(filename = 'log.txt', filemode = 'a', level = logging.NOTSET, format = '%(asctime)s - %(levelname)s: %(message)s')
    logging.debug('this is a message')
    logging.info("this is a info")
    logging.disable(30)#logging.WARNING
    logging.warning("this is a warnning")
    logging.critical("this is a critical issue")
    logging.error("this is a error")
    logging.addLevelName(88,"MyCustomError")
    logging.log(88,"this is an my custom error")
    try:
      raise Exception('this is a exception')
    except:
      logging.exception( 'exception')
    logging.shutdown() TestLogBasic()

Note :(this example is the simplest use to log to a log file)

1) logging.basicconfig () defines the default log to log.txt, the log file is in append mode, and all logging whose level is greater than logging.notset is handled. The log format is defined as '%(asctime)s - %(levelname)s: %(message)s';

2) logging.debug()... So log of the corresponding level;

3) disable a logging level with logging.disable();

4) use logging.addlevelname to increase the logging level;

5) use logging.log to log the log of logging level;

The log of the output text is as follows:


2011-01-18 10:02:45,415 - DEBUG: this is a message
2011-01-18 10:02:45,463 - INFO: this is a info
2011-01-18 10:02:45,463 - CRITICAL: this is a critical issue
2011-01-18 10:02:45,463 - ERROR: this is a error
2011-01-18 10:02:45,463 - MyCustomError: this is an my custom error
2011-01-18 10:02:45,463 - ERROR: exception
Traceback (most recent call last):
  File "testlog.py", line 15, in TestLogBasic
    raise Exception('this is a exception')
Exception: this is a exception

Ii. Logging level


#logging level
#logging.NOTSET 0
#logging.DEBUG 10
#logging.INFO 20
#logging.WARNING 30
#logging.ERROR 40
#logging.CRITICAL 50

The level of logging corresponds to an int, such as 10,20... Logging levels can be customized.

You can use logging.setlevel () to specify the level of logger to be handled, for example my_logger.setlevel (logging.debug) to handle only logging whose level is greater than 10.
 

Third, Handlers

Handler defines how the log is stored and displayed.

NullHandler doesn't do anything.

The StreamHandler instance sends an error to the stream (a file-like object).
The FileHandler instance sends an error to the disk file.
BaseRotatingHandler is the base class for all round dependency logs and cannot be used directly. But you can use RotatingFileHandler and TimeRotatingFileHandler.
The RotatingFileHandler instance sends information to disk files, limits the maximum log file size, and rounds it when necessary.
The TimeRotatingFileHandler instance sends an error message to disk and rounds at the appropriate event intervals.
The SocketHandler instance sends logs to the TCP/IP socket.
The DatagramHandler instance sends an error message over the UDP protocol.
The SMTPHandler instance sends an error message to a specific email address.
The SysLogHandler instance sends logs to the UNIX syslog service and supports the remote syslog service.
The NTEventLogHandler instance sends the log to the WindowsNT/2000/XP event log.
The MemoryHandler instance sends the log to the buffer in memory and clears it when certain conditions are reached.
The HTTPHandler instance sends an error message to the HTTP server, either through the GET or POST methods.
The NullHandler, StreamHandler, and FileHandler classes are all defined in the core logging module. Other handlers are defined in submodules called logging.handlers.

There is also a logging.config module that provides configuration.

FileHandler + StreamHandler


def TestHanderAndFormat():
    import logging
    logger = logging.getLogger("simple")
    logger.setLevel(logging.DEBUG)
   
    # create file handler which logs even debug messages
    fh = logging.FileHandler("simple.log")
    fh.setLevel(logging.DEBUG)
   
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
   
    # create formatter and add it to the handlers
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
   
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)     # "application" code
    logger.debug("debug message")
    logger.info("info message")
    logger.warn("warn message")
    logger.error("error message")
    logger.critical("critical message") TestHanderAndFormat()

Note: this instance USES both FileHandler and StreamHandler to write logs to files and the console.

1) use logging.getlogger () to create a new named logger;

2) logging.filehandler () is used to generate the FileHandler to write the log to the log file, and logger.addhandler () is used to bind the handler to the logger.

3) logging.streamhandler () is used to generate the StreamHandler to write the log to the console, and logger.addhandler () is used to bind the handler to the logger.

4) use logging.formatter () to construct an instance of log format, and use handler.setformatter () to bind Formatter to handler;

  The results

Simple. TXT


2011-01-18 11:25:57,026 - simple - DEBUG - debug message
2011-01-18 11:25:57,072 - simple - INFO - info message
2011-01-18 11:25:57,072 - simple - WARNING - warn message
2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

The console


2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

Fifth, RotatingFileHandler


def TestRotating():
    import glob
    import logging
    import logging.handlers
   
    LOG_FILENAME = 'logging_rotatingfile_example.out'     # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('MyLogger')
    my_logger.setLevel(logging.DEBUG)     # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)     my_logger.addHandler(handler)     # Log some messages
    for i in range(20):
        my_logger.debug('i = %d' % i)     # See what files are created
    logfiles = glob.glob('%s*' % LOG_FILENAME)     for filename in logfiles:
        print(filename)
       
TestRotating()

Description:

RotatingFileHandler specifies the maximum size of a single log file and the maximum number of log files. If the file is larger than the maximum, it will be divided into multiple files. If the number of log files is larger than the maximum number, the oldest log file will be deleted. For example, the latest log in this example is always in logging_rotatingfile_example.out, and logging_rotatingfile_example.out.5 contains the oldest log.

Operation results:


logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5

Use fileConfig to use logger


import logging
import logging.config logging.config.fileConfig("logging.conf") # create logger
logger = logging.getLogger("simpleExample") # "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

The logging.conf file is as follows:


[loggers]
keys=root,simpleExample [handlers]
keys=consoleHandler [formatters]
keys=simpleFormatter [logger_root]
level=DEBUG
handlers=consoleHandler [logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0 [handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,) [formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

Operation results:


2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message


Related articles: