Python: Introduction to the Logging module

Source: Internet
Author: User

The logging module is a built-in module of python. The main function of logging is that it can be shared between modules and different log levels are provided. Each module sends logs to the same file or other places, the most common scenario is to record information in a log file.

1. Log level of logging

'''Python
 
In [6]: import logging
 
In [7]: logging. NOTSET
Out [7]: 0
 
In [8]: logging. DEBUG
Out [8]: 10
 
In [9]: logging. INFO
Out [9]: 20
 
In [10]: logging. WARN
Out [10]: 30
 
In [11]: logging. ERROR
Out [11]: 40
 
In [12]: logging. CRITICAL
Out [12]: 50
 
In [13]: logging. _ levelNames
Out [13]:
{0: 'notset ',
10: 'debug ',
20: 'info ',
30: 'warning ',
40: 'Error ',
50: 'Critical ',
'Critical ': 50,
'Debug': 10,
'Error': 40,
'Info': 20,
'Notset': 0,
'Warn': 30,
'Warning': 30}
'''
The logging module has six levels, as shown below:

Level Value Usage
CRITICAL 50 serious error, indicating that the program is no longer running
ERROR 40 is a serious problem and the program cannot execute some functions.
WARNING 30 may cause problems in the future, but it can run
INFO 20 certifiers work as expected
DEBUG 10 is used for debugging.
NOTSET 0 stores all information output by the program.
Example:
 
 
#! /Usr/bin/env python
# Coding: UTF-8
 
Import logging
 
# Set the log file used, log level, and file read/write mode
Logging. basicConfig (filename = 'example. Log', level = logging. DEBUG, filemode = 'w ')
Logging. debug ('this is debug level ')
Logging.info ('this is info level ')
Logging. warning ('this is warning level ')
Logging. error ('this is error level ')
Logging. critical ('this is critical level ')
View Logs
# Cat example. log
DEBUG: root: This is debug level
INFO: root: This is info level
WARNING: root: This is warning level
ERROR: root: This is error level
CRITICAL: root: This is critical level
 
Note: The log output level of the logging module is the warning level by default, so all logs smaller than the default level will not be written to files. Root indicates the log-level root node.
2. Custom Log output format

The format parameter allows you to customize the format of the log file to be written.
 
 
Import logging
Logging. basicConfig (format = '% (levelname) s: % (message) s', level = logging. DEBUG)
Or use the following methods in more detail, which is also a common method:

Logging. basicConfig (
Level = logging. DEBUG,
Format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ',
Datefmt = '% Y-% m-% d % H: % M: % s ',
Filename = OS. path. join (LOG_PATH, 'example. Log '),
Filemode = 'A'
    )
The output format is as follows:

23:43:23 log. py [line: 23] DEBUG This is debug level
 
3. Record logs from multiple different modules

The logging module provides more powerful components for logging, loggers, handlers, filters, and formatters in multiple different modules.

The Logger recorder exposes interfaces that can be directly used by application code.
Handler processor that sends (recorded by the recorder) logs to a suitable destination.
Filter filters provide better granularity control, which determines which log records are output.
Formatter, indicating the layout of log records in the final output.
Log records are executed by calling the logger object method. Each module needs to create a logger object. To distinguish the logs of each module, a good naming style is to use the module name. In each module that uses logger, the name is as follows:

 
Logger = logging. getLogger (_ file __)
 
This means that the logger name can be tracked as the package/module level, and you can intuitively observe which module outputs the event.

The preceding component can be used to output logs to both the terminal and log.txt files.

 
Import logging
 
# If not specified, the root
Logger = logging. getLogger (_ file __)
Logger. setLevel (logging. DEBUG)
 
# Create a handler and write it to log.txt
# Logging. FileHandler (self, filename, mode = 'a', encoding = None, delay = 0)
Handle = logging.FileHandler('log.txt ')
Handle. setLevel (logging. DEBUG)
 
# Create a handler and output the log to terminal
Terminal = logging. StreamHandler ()
Terminal. setLevel (logging. DEBUG)
 
# Specify the output format
Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')
Handle. setFormatter (formatter)
Terminal. setFormatter (formatter)
 
# Add handler to logger
Logger. addHandler (handle)
Logger. addHandler (terminal)
 
# Writing logs
Logger. debug ('debug ')
Logger.info ('info ')
Output:

00:09:05, 212-B. py-DEBUG-Debug
00:09:05, 213-B. py-INFO-Info
 
Examples of using multiple modules:
'Log. Py' file:
 
#! /Usr/bin/env python
# Coding = UTF-8
 
_ Author _ = 'tianfeiyu'
 
 
Import OS
Import logging
 
 
LOG_PATH = OS. path. abspath (OS. path. join (_ file __,'..'))
 
Logging. basicConfig (
Level = logging. INFO,
Format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ',
Datefmt = '% Y-% m-% d % H: % M: % s ',
Filename = OS. path. join (LOG_PATH, 'chatroom. Log '),
Filemode = 'A'
    )
       
'Client. Py' file:
 
 
Import logging
 
Logger = logging. getLogger (_ name __)
Logger. error ('this is error level ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.