想要用django的logging日志功能,获取对数据库的操作日志及捕获异常该怎么做。(官方的日志拓展功能包含了这部分,但如何使用并没看明白)
官方文档:https://docs.djangoproject.com/zh-hans/3.2/topics/logging/
下面是存储django日志的一个配置,你放置在setting.py即可,文件夹不用创建,会自动创建,你也可以指定日志文件夹
import time
cur_path = os.path.dirname(os.path.realpath(__file__)) # log_path是存放日志的路径
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
if not os.path.exists(log_path): os.mkdir(log_path) # 如果不存在这个logs文件夹,就自动创建一个
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': True,
# 'formatters': {
# # 日志格式
# 'standard': {
# 'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
# '[%(levelname)s]- %(message)s'},
# 'myconsole': {
# 'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s]- %(message)s'},
# 'simple': { # 简单格式
# 'format': '%(levelname)s %(message)s'
# },
# },
# # 过滤
# 'filters': {
# 'require_debug_false': {
# '()': 'django.utils.log.RequireDebugFalse',
# },
# 'require_debug_true': {
# '()': 'django.utils.log.RequireDebugTrue',
# },
# },
# # 定义具体处理日志的方式
# 'handlers': {
# # 默认记录所有日志
# 'default': {
# 'level': 'INFO',
# 'class': 'logging.handlers.RotatingFileHandler',
# 'filename': os.path.join(log_path, 'all-{}.log'.format(time.strftime('%Y-%m-%d'))),
# 'maxBytes': 1024 * 1024 * 5, # 文件大小
# 'backupCount': 5, # 备份数
# 'formatter': 'standard', # 输出格式
# 'encoding': 'utf-8', # 设置默认编码,否则打印出来汉字乱码
# },
# # 输出错误日志
# 'error': {
# 'level': 'ERROR',
# 'class': 'logging.handlers.RotatingFileHandler',
# 'filename': os.path.join(log_path, 'error-{}.log'.format(time.strftime('%Y-%m-%d'))),
# 'maxBytes': 1024 * 1024 * 5, # 文件大小
# 'backupCount': 5, # 备份数
# 'formatter': 'standard', # 输出格式
# 'encoding': 'utf-8', # 设置默认编码
# },
# # 控制台输出
# 'console': {
#
# 'level': 'DEBUG',
# 'filters': ['require_debug_true'],
# 'class': 'logging.StreamHandler',
# 'stream': 'ext://sys.stdout',
# # 'stream': open(os.path.join(log_path, 'print-{}.log'.format(time.strftime('%Y-%m-%d'))), 'a'),
# # 虽然成功了,但是并没有将所有内容全部写入文件,目前还不清楚为什么
# 'formatter': 'standard', # 制定输出的格式,注意 在上面的formatters配置里面选择一个,否则会报错
# # 'encoding': 'utf-8', # 设置默认编码
# },
# # 输出info日志
# 'info': {
# 'level': 'INFO',
# 'class': 'logging.handlers.RotatingFileHandler',
# 'filename': os.path.join(log_path, 'info-{}.log'.format(time.strftime('%Y-%m-%d'))),
# 'maxBytes': 1024 * 1024 * 5,
# 'backupCount': 5,
# 'formatter': 'standard',
# 'encoding': 'utf-8', # 设置默认编码
# }, # 输出警告日志
# 'warning': {
# 'level': 'WARNING',
# 'class': 'logging.handlers.RotatingFileHandler',
# 'filename': os.path.join(log_path, 'warning-{}.log'.format(time.strftime('%Y-%m-%d'))),
# 'maxBytes': 1024 * 1024 * 5,
# 'backupCount': 5,
# 'formatter': 'standard',
# 'encoding': 'utf-8', # 设置默认编码
# }, # 输出严重错误日志
# 'critical': {
# 'level': 'CRITICAL',
# 'class': 'logging.handlers.RotatingFileHandler',
# 'filename': os.path.join(log_path, 'critical-{}.log'.format(time.strftime('%Y-%m-%d'))),
# 'maxBytes': 1024 * 1024 * 5,
# 'backupCount': 5,
# 'formatter': 'myconsole',
# 'encoding': 'utf-8', # 设置默认编码
# }, # 输出警告日志
# },
# # 配置用哪几种 handlers 来处理日志
# 'loggers': {
# # 类型 为 django 处理所有类型的日志, 默认调用
# 'django': {
# 'handlers': ['console', 'error', 'info', 'warning', 'critical', 'console'],
# 'level': 'INFO',
# 'propagate': False
# },
# # log 调用时需要当作参数传入
# 'log': {
# 'handlers': ['error', 'info', 'console', 'default'],
# 'level': 'INFO',
# 'propagate': True
# },
# }
# }
loggers中的django配置为django运行时调用的配置文件,handlers中的所有项都会被记录到文件中,log为自定义日志,你可以调用django的日志系统,写自定义日志,
有帮助请采纳,谢谢
#记录对数据库的操作输出到控制台
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level': 'DEBUG',
},
对数据库进行操作的记录能输出到控制台了,但是我想进一步只获取更新、删除、创建操作,排除掉select操作。不知道该怎么做
我们可以从 django.db 模块导入这些异常。这个实现背后的想法是:
Django封装了标准的数据库异常。并且,当异常发生时,我们的Python代码可以与数据库异常相对应。这使得在特定级别上很容易在Python中处理数据库异常。
Django 提供的异常包装器的工作方式与 Python 数据库 API 相同。
错误是:
接口错误
数据库错误
数据错误
完整性错误
内部错误
编程错误
不支持错误
我们在以下情况下引发这些错误:
找不到数据库
接口不存在
数据库未连接
输入数据无效等。
https://blog.csdn.net/weixin_39604350/article/details/111742074
import logging
from logging import handlers
class Logger(object):
level_relations = {
'debug':logging.DEBUG,
'info':logging.INFO,
'warning':logging.WARNING,
'error':logging.ERROR,
'crit':logging.CRITICAL
}#日志级别关系映射
def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt)#设置日志格式
self.logger.setLevel(self.level_relations.get(level))#设置日志级别
sh = logging.StreamHandler()#往屏幕上输出
sh.setFormatter(format_str) #设置屏幕上显示的格式
th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
#实例化TimedRotatingFileHandler
#interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
# S 秒
# M 分
# H 小时、
# D 天、
# W 每星期(interval==0时代表星期一)
# midnight 每天凌晨
th.setFormatter(format_str)#设置文件里写入的格式
self.logger.addHandler(sh) #把对象加到logger里
self.logger.addHandler(th)
if __name__ == '__main__':
log = Logger('all.log',level='debug')
log.logger.debug('debug')
log.logger.info('info')
log.logger.warning('警告')
log.logger.error('报错')
log.logger.critical('严重')
Logger('error.log', level='error').logger.error('error')