Django logging日志模块
在setting.py文件中添加:
# BASE_DIR/logs 存放日志的路径,BASE_DIR项目根目录
log_path = os.path.join(BASE_DIR, 'logs')
if not os.path.exists(log_path):
os.mkdir(log_path) # 如果不存在这个logs文件夹,就自动创建一个
LOGGING = {
"version": 1, # 版本
"disable_existing_loggers": False, # 是否禁止默认配置的记录器
"formatters": {
"verbose": {
"format": "{asctime} {module} {process:d} {thread:d} {levelname} {message}",
"style": "{",
},
"simple": {
"format": "{levelname} {message}",
"style": "{",
},
"standard": {
"format": "[%(asctime)s] %(filename)s [%(funcName)s:%(lineno)d] [%(process)d] [%(thread)d] "
"%(levelname)s - %(message)s",
},
},
# 过滤
"filters": {
},
# 定义具体处理日志的方式
"handlers": {
# 控制台输出
"console": {
"level": "INFO",
"class": "logging.StreamHandler",
"formatter": "standard",
},
# 默认记录所有日志
"debug_file": {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'debug.log'),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'formatter': 'standard', # 输出格式
'encoding': 'utf-8', # 设置默认编码,否则打印出来汉字乱码
},
# 输出错误日志
"error_file": {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'error.log'),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'formatter': 'standard', # 输出格式
'encoding': 'utf-8', # 设置默认编码
},
"warning_file": {
'level': 'WARNING',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'warning.log'),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'formatter': 'standard', # 输出格式
'encoding': 'utf-8', # 设置默认编码
},
# 输出info日志
"info_file": {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path, 'info.log'),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8', # 设置默认编码
},
},
# 配置用哪几种 handlers 来处理日志
"loggers": {
'default': {
'handlers': ['debug_file', 'info_file', 'warning_file', 'error_file', 'console'],
'level': "INFO",
},
"django": {
"handlers": ["console", "debug_file"],
"level": "INFO",
"propagate": False,
},
# log 调用时需要当作参数传入
'log': {
'handlers': ['debug_file', 'info_file', 'warning_file', 'error_file', 'console'],
'level': 'INFO',
'propagate': True
},
},
}
在视图中调用日志,打印内容:
import logging
logger = logging.getLogger("default")
def output_log():
logger.info("============= 日志打印 ===========")
在项目根目录下的logs/
目录下,存在debug.log, info.log, warning.log, error.log
日志文件,可查看到日志打印的内容信息。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)