杰瑞科技汇

Python logger 列表如何获取与管理?

Of course! When you ask for a "Python logger list," you could mean a few different things. I'll cover the most common interpretations:

Python logger 列表如何获取与管理?-图1
(图片来源网络,侵删)
  1. How to get a list of all loggers currently in use.
  2. A list of the most common and useful logging handlers.
  3. A list of standard logging levels.

Let's break down each one.


How to Get a List of All Loggers

Python's logging module maintains a global dictionary of all loggers that have been referenced, accessed via logging.Logger.manager.loggerDict. You can iterate through this to see what's available.

This is useful for debugging or understanding the state of your application's logging setup.

Example: Listing All Loggers

import logging
import logging.config
# --- Setup some loggers to demonstrate ---
# Create a custom logger
my_app_logger = logging.getLogger("my_app_module")
my_app_logger.setLevel(logging.DEBUG)
# Create another one
another_logger = logging.getLogger("another_service.another_module")
another_logger.setLevel(logging.INFO)
# The root logger is also in the dictionary
root_logger = logging.getLogger()
# --- Now, let's list them all ---
print("List of all loggers in the system:")
print("=" * 40)
# logging.Logger.manager.loggerDict is a dictionary of all named loggers
# The root logger is stored under the key '' (empty string)
all_loggers = logging.Logger.manager.loggerDict
for name in all_loggers:
    logger = all_loggers[name]
    # Check if it's a real Logger instance and not a placeholder
    if isinstance(logger, logging.Logger):
        # Get effective level (e.g., DEBUG, INFO, WARNING)
        level_name = logging.getLevelName(logger.getEffectiveLevel())
        print(f"- Logger Name: '{name}'")
        print(f"  Level: {level_name}")
        print(f"  Propagate: {logger.propagate}")
        print(f"  Handlers: {logger.handlers}")
        print("-" * 20)

Output of the example:

Python logger 列表如何获取与管理?-图2
(图片来源网络,侵删)
List of all loggers in the system:
========================================
- Logger Name: 'my_app_module'
  Level: DEBUG
  Propagate: True
  Handlers: []
--------------------
- Logger Name: 'another_service.another_module'
  Level: INFO
  Propagate: True
  Handlers: []
--------------------
- Logger Name: ''
  Level: WARNING
  Propagate: False
  Handlers: [<StreamHandler <stderr> (NOTSET)>]
--------------------

Key points from the output:

  • 'my_app_module' and 'another_service.another_module' are the custom loggers we created.
  • is the root logger. It's always present and is the ultimate ancestor of all other loggers.
  • Level: This is the effective level, which is the level the logger will actually use (considering its own level and its parent's level).
  • Propagate: If True, messages are passed up to the parent logger.
  • Handlers: A list of handlers attached directly to this logger. Our custom loggers have none, so they rely on propagation to the root logger, which has a StreamHandler that prints to the console (stderr).

List of Common and Useful Logging Handlers

Handlers are what determine where your log messages go. You "attach" them to a logger. Here is a list of the most common ones with examples.

Handler Purpose Common Use Case
StreamHandler Sends log records to a stream (like sys.stdout or sys.stderr). Console output for debugging and development.
FileHandler Sends log records to a disk file. Storing logs for long-term analysis and auditing.
RotatingFileHandler Sends logs to a file, but when the file reaches a certain size, it's "rotated" (renamed) and a new file is started. Prevents log files from growing indefinitely. Keeps the last N files.
TimedRotatingFileHandler Like RotatingFileHandler, but based on time (e.g., a new file every day or midnight). Creating daily, weekly, or monthly log archives.
SysLogHandler Sends log records to a Unix syslog daemon. System-wide logging on Linux/macOS servers.
SMTPHandler Sends log records via email. Critical error notifications (e.g., when the application crashes).
HTTPHandler Sends log records to an HTTP endpoint (like a web server). Forwarding logs to a centralized logging service (e.g., Loggly, Datadog).
NullHandler Does nothing. Used to "silence" a logger that you don't want to output anything. Best practice for libraries.

Example: Using Different Handlers

import logging
import logging.handlers
from datetime import datetime
# --- Setup a logger ---
logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG) # Set the lowest level this logger will handle
# --- Create Formatters ---
# A simple formatter for the console
simple_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# A more detailed formatter for the file
detailed_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(lineno)d - %(message)s')
# 1. StreamHandler (for console output)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO) # Show INFO and above on console
console_handler.setFormatter(simple_formatter)
logger.addHandler(console_handler)
# 2. RotatingFileHandler (for disk files)
# Rotates at 1KB, keeps 3 backup files
file_handler = logging.handlers.RotatingFileHandler(
    'app.log', maxBytes=1000, backupCount=3
)
file_handler.setLevel(logging.DEBUG) # Log everything to the file
file_handler.setFormatter(detailed_formatter)
logger.addHandler(file_handler)
# 3. TimedRotatingFileHandler (for daily logs)
# Rotates at midnight, keeps 7 days of backups
daily_handler = logging.handlers.TimedRotatingFileHandler(
    'app_daily.log', when='midnight', interval=1, backupCount=7
)
daily_handler.setLevel(logging.WARNING) # Only log warnings and errors to the daily log
daily_handler.setFormatter(simple_formatter)
logger.addHandler(daily_handler)
# --- Now let's log some messages ---
logger.debug("This is a debug message. It will go to app.log only.")
logger.info("This is an info message. It will go to console and app.log.")
logger.warning("This is a warning. It will go to console, app.log, and app_daily.log.")
logger.error("This is an error. It will go to console, app.log, and app_daily.log.")
# Check your directory for 'app.log' and 'app_daily.log'

List of Standard Logging Levels

Loggers and handlers have a level. A message will only be processed if its severity is greater than or equal to the logger's or handler's level.

Level Numeric Value Description
CRITICAL 50 Very serious errors, indicating that the program itself may be unable to continue running.
ERROR 40 Due to a more serious problem, the software has not been able to perform some function.
WARNING 30 An indication that something unexpected happened, or a problem might occur in the near future (e.g., ‘disk space low’). The software is still working as expected.
INFO 20 Confirmation that things are working as expected.
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.

You can also define your own custom levels, but it's generally recommended to stick to the standard ones.

Python logger 列表如何获取与管理?-图3
(图片来源网络,侵删)

Example: How Levels Work

import logging
# Create a logger
logger = logging.getLogger("level_demo")
logger.setLevel(logging.DEBUG) # Logger will handle DEBUG and above
# Create a handler that only handles WARNING and above
warning_handler = logging.StreamHandler()
warning_handler.setLevel(logging.WARNING)
# Create a handler that only handles ERROR and above
error_handler = logging.FileHandler('errors.log')
error_handler.setLevel(logging.ERROR)
# Add handlers to the logger
logger.addHandler(warning_handler)
logger.addHandler(error_handler)
print("--- Logging messages ---")
logger.debug("This is a debug message. It will be ignored by both handlers.")
logger.info("This is an info message. It will be ignored by both handlers.")
logger.warning("This is a warning. It will be handled by the StreamHandler.")
logger.error("This is an error. It will be handled by BOTH handlers.")
# Check your console and the 'errors.log' file to see the difference.

Console Output:

--- Logging messages ---
2025-10-27 10:30:00,123 - level_demo - WARNING - This is a warning. It will be handled by the StreamHandler.
2025-10-27 10:30:00,124 - level_demo - ERROR - This is an error. It will be handled by BOTH handlers.

Content of errors.log:

2025-10-27 10:30:00,124 - level_demo - ERROR - This is an error. It will be handled by BOTH handlers.
分享:
扫描分享到社交APP
上一篇
下一篇