Python logging Module
In programming, logging is a very important tool that helps us track the running state of a program, debug errors, and record important information.
Python provides a built-in logging module, dedicated to handling logging tasks. Compared with the simple print statement, thelogging module is more flexible and powerful, capable of meeting logging needs in different scenarios.
Why use the logging module?
- Flexibility:
loggingmodule allows you to set the log level, format, and output location as needed. - Extensibility: You can easily output logs to different targets such as files, consoles, and networks.
- Structured logging:
loggingmodule supports structured logging, facilitating subsequent analysis and processing. - Performance optimization: Together with
printCompared tologgingmodule is optimized for performance and is suitable for use in production environments.
Basic Usage of the logging Module
1. Import the logging module
First, we need to import the logging module:
Example
import
logging
2. Configure the log level
The log level is used to control the verbosity of the logs.logging module provides the following log levels:
- DEBUG: Detailed debugging information, usually used during development.
- INFO: Information when the program runs normally.
- WARNING: Indicates a potential problem, but the program can still run normally.
- ERROR: Indicates an error in the program that prevents some functions from working properly.
- CRITICAL: Indicates a serious error that may cause the program to crash.
You can set the log level with the following code:
Example
logging
.
basicConfig
(
level
=
logging
.
DEBUG
)
3. Record logs
After setting the log level, you can use the following methods to record logs:
Example
logging
.
debug
(
"This is a debug message"
)
logging
.
info
(
"This is an info message"
)
logging
.
warning
(
"This is a warning message"
)
logging
.
error
(
"This is an error message"
)
logging
.
critical
(
"This is a critical error message"
)
4. Log output format
You can use basicConfig method to customize the output format of logs. For example:
Example
logging
.
basicConfig
(
level
=
logging
.
DEBUG
,
format
=
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
,
datefmt
=
"%Y-%m-%d %H:%M:%S"
)
5. Output logs to a file
By default, logs are output to the console. If you want to save logs to a file, you can configure it like this:
Example
logging
.
basicConfig
(
level
=
logging
.
DEBUG
,
format
=
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
,
filename
=
"app.log"
)
Advanced Usage of the logging Module
1. Use multiple loggers
In large projects, you may need to create independent loggers for different modules or components. This can be achieved as follows:
Example
logger
=
logging
.
getLogger
(
"my_logger"
)
logger.
setLevel
(
logging
.
DEBUG
)
Create a file handler
file_handler
=
logging
.
FileHandler
(
"my_logger.log"
)
file_handler.
setLevel
(
logging
.
DEBUG
)
Create a console handler
console_handler
=
logging
.
StreamHandler
(
)
console_handler.
setLevel
(
logging
.
INFO
)
Set the log format
formatter
=
logging
.
Formatter
(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
file_handler.
setFormatter
(
formatter
)
console_handler.
setFormatter
(
formatter
)
Add the handler to the logger
logger.
addHandler
(
file_handler
)
logger.
addHandler
(
console_handler
)
Record logs
logger.
debug
(
"This is a debug message"
)
logger.
info
(
"This is an info message"
)
2. Log filters
You can use filters to control which logs need to be recorded. For example:
Example
class
MyFilter
(
logging
.
Filter
)
:
def
filter
(
self
,
record
)
:
return
record.
levelno
==
logging
.
ERROR
logger.
addFilter
(
MyFilter
(
)
)
3. Log rotation
When the log file becomes too large, you can use RotatingFileHandler or TimedRotatingFileHandler to implement log rotation:
Example
from
logging
.
handlers
import
RotatingFileHandler
handler
=
RotatingFileHandler
(
"app.log"
,
maxBytes
=
1024
,
backupCount
=
3
)
logger.
addHandler
(
handler
)
Common Attributes and Methods of the logging Module
1. Core classes
| class | Description | Example |
|---|---|---|
logging.Logger |
logger, used to emit log messages (obtained via logging.getLogger(name) ) |
logger = logging.getLogger("my_logger") |
logging.Handler |
handler, determines the log output location (such as file, console, etc.) | handler = logging.FileHandler("app.log") |
logging.Formatter |
formatter, controls the output format of the log | formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') |
logging.Filter |
filter, used for finer-grained control over logging | filter = logging.Filter("module.name") |
2. Logger Object Common Methods
| Method | Description | Example |
|---|---|---|
logger.setLevel(level) |
set the log level (such as logging.DEBUG、logging.INFO) |
logger.setLevel(logging.DEBUG) |
logger.debug(msg) |
record DEBUG level logs | logger.debug("调试信息") |
logger.info(msg) |
record INFO level logs | logger.info("程序启动") |
logger.warning(msg) |
record WARNING level logs | logger.warning("磁盘空间不足") |
logger.error(msg) |
record ERROR level logs | logger.error("操作失败") |
logger.critical(msg) |
record CRITICAL level logs | logger.critical("系统崩溃") |
logger.addHandler(handler) |
add a handler | logger.addHandler(handler) |
logger.addFilter(filter) |
Add a filter | logger.addFilter(filter) |
3. Common Handler Types
| Handler Type | Description | Example |
|---|---|---|
StreamHandler |
Output to a stream (e.g., console) | handler = logging.StreamHandler() |
FileHandler |
Output to a file | handler = logging.FileHandler("app.log") |
RotatingFileHandler |
Split logs by file size | handler = logging.RotatingFileHandler("app.log", maxBytes=1e6, backupCount=3) |
TimedRotatingFileHandler |
Split logs by time | handler = logging.TimedRotatingFileHandler("app.log", when="midnight") |
SMTPHandler |
Send logs via email | handler = logging.SMTPHandler("mail.example.com", "from@example.com", "to@example.com", "Error Log") |
4. Log Levels (Constants)
| Level | Value | Description |
|---|---|---|
CRITICAL |
50 | Critical error, the program may be unable to continue running |
ERROR |
40 | Error, but the program can still run |
WARNING |
30 | Warning information (default level) |
INFO |
20 | Program running information |
DEBUG |
10 | Debug information |
NOTSET |
0 | Inherit the level of the parent logger |
5. Common Formatter Format Fields
| Field | Description | Example output |
|---|---|---|
%(asctime)s |
Log creation time | 2023-01-01 12:00:00,123 |
%(levelname)s |
Log level name | INFO |
%(message)s |
Log message content | 程序启动成功 |
%(name)s |
Logger name | my_logger |
%(filename)s |
Name of the file that generated the log | app.py |
%(lineno)d |
Line number where the log was generated | 42 |
%(funcName)s |
Name of the function that generated the log | main |
6. Quick Configuration Methods
| Method | Description | Example |
|---|---|---|
logging.basicConfig() |
Configure log level, handlers, and format in one step (usually called at the program entry point) | logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s') |
Common parameters:
-
level: Set the root logger level -
filename: Output to a file -
filemode: File mode (e.g.'w'overwrite) -
format: Format string -
datefmt: Date format (e.g."%Y-%m-%d %H:%M:%S")
Example
- Basic configuration
Example
import
logging
Configure logging
logging
.
basicConfig
(
level
=
logging
.
DEBUG
,
format
=
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
,
filename
=
'app.log'
)
Use
logger
=
logging
.
getLogger
(
"my_app"
)
logger.
info
(
"Program started"
)
- Complex configuration with multiple handlers
Example
import
logging
Create a logger
logger
=
logging
.
getLogger
(
"my_module"
)
logger.
setLevel
(
logging
.
DEBUG
)
Console handler
console_handler
=
logging
.
StreamHandler
(
)
console_handler.
setLevel
(
logging
.
WARNING
)
File handler
file_handler
=
logging
.
FileHandler
(
"debug.log"
)
file_handler.
setLevel
(
logging
.
DEBUG
)
Formatting
formatter
=
logging
.
Formatter
(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
console_handler.
setFormatter
(
formatter
)
file_handler.
setFormatter
(
formatter
)
add a handler
logger.
addHandler
(
console_handler
)
logger.
addHandler
(
file_handler
)
Use
logger.
debug
(
"Debug information"
)
Write to file only
logger.
warning
(
"Warning!"
)
Output to both console and file
3. Log Rotation
Example
from
logging
.
handlers
import
RotatingFileHandler
handler
=
RotatingFileHandler
(
"app.log"
,
maxBytes
=
1e6
,
backupCount
=
3
1MB per file, keep 3 backups
)
logger.
addHandler
(
handler
)