Basic Usage of logging Module of Python

  • 2021-08-31 08:36:48
  • OfStack

When the server is deployed, it often runs in the background. When a specific error occurs in the program, I want to be able to query in the log. Therefore, you are familiar with the usage of the following logging module.

The logging module defines the standard API for reporting error and status information.

Components of logging

The log system has four interactive components. We need to use the Logger instance to add information to the log. The trigger log creates an LogRecord for storing information in memory. Logger may have many Handler objects for receiving and processing log records. Handler uses Formatter to output log records.

Enter a log to a file

Most applications input logs to files. The basicConfig () function allows you to set the default handler, allowing the log to be entered into a file.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging

LOG_FILENAME = 'log.txt'
logging.basicConfig(
  filename=LOG_FILENAME,
  level=logging.DEBUG,
)

logging.debug('hello logging!')

with open(LOG_FILENAME, 'rt') as f:
  body = f.read()

print('FILE: ')
print(body)

The output after running the script is as follows:

FILE:
DEBUG:root:hello logging!

Circulation of log files

To generate a new file each time the program runs, pass an filemode parameter with the value w to basicConfig (). A more convenient method is to use RotatingFileHandler, which can automatically create files and save old files at the same time.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import logging.handlers

LOG_FILENAME = 'log.txt'

my_logger = logging.getLogger('SpecificLogger')
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(f'i = {i}')

# See what files are created
log_files = glob.glob(f'{LOG_FILENAME}*')
for filename in sorted(log_files):
  print(filename)

The output after running the script is as follows:

log.txt
log.txt.1
log.txt.2
log.txt.3
log.txt.4
log.txt.5

Cashback, log. txt stores the latest content, and logging automatically renames these files.

Level of information display

logging has different logging levels.

级别(level) 值(value)
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
UNSET 0

The log can only be triggered if it is above a certain level 1.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys

level = int(sys.argv[1])
logging.basicConfig(
  level=level
)

logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

$ python logging_level.py 10
DEBUG:root:debug message
INFO:root:info message
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
$ python logging_level 40
ERROR:root:error message
CRITICAL:root:critical message

Naming logging Instances


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging

logging.basicConfig(
  level=logging.WARNING
)

logger1 = logging.getLogger('package1.module1')
logger2 = logging.getLogger('package2.module2')

logger1.warning('hello 1')
logger2.warning('hello 2')

Output after running the script:

WARNING:package1.module1:hello 1
WARNING:package2.module2:hello 2

The above is the logging module of Python basic usage details, more information about Python logging module please pay attention to other related articles on this site!


Related articles: