1. Built-in logger
The logging module in the Python standard library provides logging functionality
Allows the developer to pass theCreating loggers, handlers and formattersto control log generation and output
Here are some of the main components and concepts of the logging module:
-
Logger: Main entry point to the entire logging system
Each logging operation is performed through a specific logger. Typically, each module or subsystem creates its own logger
utilization(name)
method to get or create a logger, where the name argument is the name of the logger. If the name argument is omitted, the root logger is returned -
Handler:
Responsible for sending logging to a specified destination, such as console, file, network, etc.
pass (a bill or inspection etc)、
and other classes to create different types of handlers
-
Formatter: defines the appearance of the log message
Customize the format of log messages by specifying a format string or use theClasses create formatters
-
Log Level:
Log level is used to indicate the importance or severity of the log message, in descending order of severity: DEBUG, INFO, WARNING, ERROR, CRITICAL.
Loggers and handlers can set a minimum logging level, and only log messages that meet or exceed that level will be processed
import logging # Create loggers logger = ('Coder Research Monk') () # Create handlers and set levels console_handler = () console_handler.setLevel() # Create formatters formatter = ('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) # Add handler to logger (console_handler) # Recording logs ('This is a debug message') ('This is an info message') ('This is a warning message') ('This is an error message') ('This is a critical message')
Screenshots are below:
If the logger is set to register as WARNING
# Create loggers logger = ('Coder Research Monk') ()
Then the output is as follows:
2. Customizing the logger
Custom Logger allows you to customize logging according to your project's needs, meeting specific logging formats, output targets, logging levels and other requirements.
By customizing Logger, you can achieve the following functions:
- Customized log format: You can define the format of the log according to your needs, including information such as time, module, level, message, etc.
- Output to different targets: Logs can be logged to different targets such as console, file, database, network, etc. for easy log viewing and management
- Flexible setting of log levels: You can set different levels of logging according to the needs of the project to meet different debugging and troubleshooting needs.
- Add additional functionality: Extend Logger's functionality by adding log archiving, compression, encryption, and more!
A logger module that can be copied in its entirety:
from datetime import datetime from os import path from sys import stdout from loguru import logger class MyLogger(object): def __init__(self, log_name, level="INFO") -> logger: () fmt = '<level>{time:YYYY-MM-DD HH:mm:ss} | {module}: {level} >> {message}</level>' (stdout, format=fmt) self.my_logger = logger _today = ().strftime("%Y_%m_%d") log_path = f"{log_name}{_today}.log" = (log_path) self.my_logger.add( log_path, encoding="utf-8", retention='7 days', rotation="50 MB", compression='zip', format=fmt, enqueue=True, level=level) def info(self, content): self.my_logger.opt(depth=1).info(content) def debug(self, content): self.my_logger.opt(depth=1).debug(content) def error(self, content, *args, **kwargs): self.my_logger.opt(depth=1).error(content) if len(args) > 0 or len(kwargs) > 0: ("Error details:", *args, **kwargs) def exception(self, content, *args, **kwargs): self.my_logger.opt(depth=1).exception(content, *args, **kwargs) def warning(self, content): self.my_logger.opt(depth=1).warning(content)
The test is as follows:
# Create a logger named "my_app" with level INFO logger = MyLogger("my_app") # Record a log at the INFO level ("This is an informational message.") # Record a DEBUG level log. ("This is a debug message.") # Record an ERROR level log ("This is an error message.") # Record a log with a WARNING level. ("This is a warning message.") # Record an ERROR level log with additional parameters and keyword arguments ("An error occurred.", "Extra info", custom_param="Custom value") # Records an ERROR level log with an exception message try: result = 1 / 0 except Exception as e: ("An error occurred while performing a calculation.")
Screenshots are below:
The overall logger file is as follows:
The above is Python custom logger module example code details, more information about Python custom logger module please pay attention to my other related articles!