import logging
def setup_custom_logger(name, log_level):
"""
创建并配置自定义日志器。
:param name: 日志器的名称
:param log_level: 日志级别,如logging.DEBUG, logging.INFO等
:return: 配置好的日志器实例
"""
# 创建日志器
logger = logging.getLogger(name)
logger.setLevel(log_level)
# 创建处理器:这里以控制台处理器为例
stream_handler = logging.StreamHandler()
stream_handler.setLevel(log_level) # 处理器级别应与日志器级别相同或更严格
# 定义日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream_handler.setFormatter(formatter)
# 添加处理器到日志器
logger.addHandler(stream_handler)
return logger
def custom_log(logger, log_level, message):
"""
自定义日志函数,根据传入的日志级别记录日志。
:param logger: 日志器实例
:param log_level: 日志级别
:param message: 日志消息
"""
if log_level == logging.DEBUG:
logger.debug(message)
elif log_level == logging.INFO:
logger.info(message)
elif log_level == logging.WARNING:
logger.warning(message)
elif log_level == logging.ERROR:
logger.error(message)
elif log_level == logging.CRITICAL:
logger.critical(message)
else:
raise ValueError("Invalid log level")
# 使用示例
logger = setup_custom_logger('MyLogger', logging.DEBUG)
custom_log(logger, logging.DEBUG, "This is a debug message")
custom_log(logger, logging.INFO, "This is an info message")
custom_log(logger, logging.WARNING, "This is a warning message")
custom_log(logger, logging.ERROR, "This is an error message")
custom_log(logger, logging.CRITICAL, "This is a critical message")
|