我有一个 logger.py 配置文件,我在 Django 项目的许多文件中使用它:
logger.py:
import datetime
import logging
import os
cwd = os.getcwd()
LOGS_PATH = os.path.join(cwd, "logs")
if not os.path.isdir(LOGS_PATH):
os.mkdir(LOGS_PATH)
class CustomFormatter(logging.Formatter):
LEVEL_COLOR_MAP = {
logging.DEBUG: "\033[96m", # Cyan
logging.INFO: "\033[92m", # Green
logging.WARNING: "\033[93m", # Yellow
logging.ERROR: "\033[91m", # Red
logging.CRITICAL: "\033[95m", # Magenta
}
def __init__(self, use_ansi=True, trim_module_name_and_time=False):
self.use_ansi = use_ansi
self.trim_module_name_and_time = trim_module_name_and_time
def format(self, record):
module_and_file_name = record.name
func_name = record.funcName
line_number = record.lineno
module = f"[{module_and_file_name}.{func_name}:{line_number}]"
if len(module) < 70:
module = module + " " * (70 - len(module))
level_name = record.levelname
if len(level_name) < 7:
level_name = level_name + " " * (7 - len(level_name))
asctime = datetime.datetime.fromtimestamp(record.created).strftime(
"%b/%d %H:%M:%S"
)
if self.use_ansi:
level_color = self.LEVEL_COLOR_MAP.get(record.levelno, "\033[97m") # White
if self.trim_module_name_and_time:
log_message = f"{level_color}{level_name}\033[0m %(message)s" % {
"levelname": level_name,
"lineno": line_number,
"message": record.getMessage(),
}
return log_message
else:
log_message = (
f"{module} [{asctime}] {level_color}{level_name}\033[0m %(message)s"
% {
"module": module,
"levelname": level_name,
"lineno": line_number,
"message": record.getMessage(),
}
)
return log_message
else:
if self.trim_module_name_and_time:
log_message = f"{level_name} %(message)s" % {
"levelname": level_name,
"lineno": line_number,
"message": record.getMessage(),
}
return log_message
else:
log_message = f"{module} [{asctime}] {level_name} %(message)s" % {
"module": module,
"levelname": level_name,
"lineno": line_number,
"message": record.getMessage(),
}
return log_message
logger_config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"custom_formatter": {"()": CustomFormatter, "use_ansi": False},
"custom_formatter_simple": {
"()": CustomFormatter,
"use_ansi": True,
"trim_module_name_and_time": True,
},
"verbose": {
"format": "%(asctime)s %(name)s:%(lineno)s [%(levelname)-7s] %(message)s [IP: {REMOTE_ADDR}]",
"datefmt": "%b/%d %H:%M:%S",
},
"simple": {"format": "%(levelname)s %(message)s"},
},
"handlers": {
"null": {
"class": "logging.NullHandler",
},
"console": {
"class": "logging.StreamHandler",
"formatter": "custom_formatter_simple",
# "level": "DEBUG",
},
"file_debug": {
"class": "logging.handlers.RotatingFileHandler",
"filename": os.path.join(LOGS_PATH, "log_debug.log"),
"backupCount": 9, # keep at most 9 log files
"maxBytes": 52428800, # 50*1024*1024 bytes (50MB)
"formatter": "custom_formatter",
# "level": "DEBUG",
},
"file_info": {
"class": "logging.handlers.RotatingFileHandler",
"filename": os.path.join(LOGS_PATH, "log_info.log"),
"backupCount": 9,
"maxBytes": 52428800,
"formatter": "custom_formatter",
# "level": "INFO",
},
},
"loggers": {
"": {
"handlers": ["file_debug", "file_info", "console"],
"level": "DEBUG",
"propagate": False,
}
},
}
例如视图.py:
import logging
from utils.logger import logger_config
logging.config.dictConfig(logger_config)
logger = logging.getLogger(__name__)
logger.info(f"Logger {__name__} initialized.")
现在我想重定向这些日志:
Not Found: /wrong_url
WARNING Not Found: /wrong_url
[30/Aug/2024 07:32:16] "GET /wrong_url HTTP/1.1" 404 5380
所以它们应该只存储在 django_debug.log 中。
我想,当我添加记录器并指定将其保存在调试文件中时,那就没问题了:
"loggers": {
"": {
"handlers": ["file_debug", "file_info", "console"],
"level": "DEBUG",
"propagate": False,
},
"django.request": {
"handlers": ["file_debug"],
"level": "WARNING",
"propagate": False,
},
},
但这不起作用。
你能指出哪里出了问题吗?即使我将其设置为仅记录到调试文件,为什么我仍然可以在控制台和 django_info.log 文件中看到警告?
预先感谢您的回复。
我想您会在控制台中看到
django.server
日志(https://docs.djangoproject.com/en/3.2/topics/logging/#django-server)。您还需要覆盖 django.server 记录器。
"loggers": {
"": {
"handlers": ["file_debug", "file_info", "console"],
"level": "DEBUG",
"propagate": False,
},
"django.request": {
"handlers": ["file_debug"],
"level": "WARNING",
"propagate": False,
},
"django.server": {
"handlers": ["file_debug"],
"level": "WARNING",
"propagate": False,
},
},
您还可以在格式化程序设置中使用
name
参数查看记录器的名称。如果您将“控制台”处理程序更改为使用“详细”格式化程序,您将看到哪个记录器将消息发送到控制台