django集成sentry实现日志上报和钉钉告警
1.实现的处理逻辑
a.在服务器用docker-compose安装sentry
b.定义类(调用请求的处理流程,在调用流程加逻辑处理,记录日志)
c.把中间件加入到django的settings,在logging部分定义日志配置
d.在settings里加sentry的配置
2.安装sentry
使用 Docker 来安装 sentry, 使用 release 版本 • https://github.com/getsentry/onpremise/releases '''得到zip包,解压,进目录''' • ./install.sh • docker-compose up -d
3.定义类,调用请求的处理流程,在处理流程中加入处理逻辑,如果有异常,实现钉钉告警和日志记录输出
(D:\djangotest\myrecrument\interview\performance.py)
class PerformanceAndExceptionLoggerMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. start_time = time.time() response = self.get_response(request) duration = time.time() - start_time response["X-Page-Duration-ms"] = int(duration * 1000) logger.info("duration:%s url:%s parameters:%s", duration, request.path, request.GET.dict() ) if duration > 0: capture_message('slow url: %s time: %s'%(request.path,duration)) # Code to be executed for each request/response after # the view is called. return response def process_exception(self, request, exception): if exception: message = "url: {url} ** msg: {error} \---------- {tb} ---------".format( url = request.build_absolute_uri(), error = repr(exception), tb = traceback.format_exc() ) logger.warning(message) # send dingtalk message #dingtalk.send(message) # capture exception to sentry: capture_exception(exception) return HttpResponse("Error processing the request, please contact the system administrator.", status=500)
4.settings
MIDDLEWARE = [ 'interview.performance.PerformanceAndExceptionLoggerMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="http://5da41243333d4f6e9b77ee8f14e06d22@129.242.147.78:34012/2", integrations=[DjangoIntegration()], # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. traces_sample_rate=1, # 采样率 send_default_pii=True #用户认证信息采集 )
效果如下:
用一个例子来演示会更加清晰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App