Sentry集成到Django环境

        

Django-Raven

Sentry支持主流语言与框架,在Python上的客户端叫做Raven,她支持Djano与Flask,也支持与WSGI兼容的应用。Raven支持1.4以上的Django版本。

DSN(Data Source Name)

想要使用Sentry,先新建项目,每个项目都具有一个PROJECT_ID与用于身份认证的 PUBLIC_KEY 和 SECRET_KEY。 DSN格式为:

1
'{PROTOCOL}://{PUBLIC_KEY}:{SECRET_KEY}@{HOST}/{PATH}{PROJECT_ID}'

 

PROTOCOL 通常是 http 或者 https。

安装django-raven

使用pip安装

1
pip install raven --upgrade

 

配置

添加app:raven.contrib.django.raven_compat

1
2
3
INSTALLED_APPS = (
'raven.contrib.django.raven_compat',
)

 

这个是通过在Django中增加了钩子函数来实现错误捕捉的

在settings中需增加RAVEN_CONFIG这个变量

1
2
3
4
5
6
7
8
9
import os
import raven
 
RAVEN_CONFIG = {
'dsn': 'http://47de9d4ae76c41c995c33c49d9d36e8c:[email protected]:9000/2',
# If you are using git, you can also automatically configure the
# release based on the git info.
'release': raven.fetch_git_sha(os.path.dirname(os.pardir)),
}

以上配置好后,便可以测试一下是否正常工作了。

1
python manage.py raven test
1
2
3
4
5
6
7
8
9
10
~/Documents/project(master*) » python3 project/manage.py raven test
Client configuration:
DEBUG Configuring Raven for host: <raven.conf.remote.RemoteConfig object at 0x7f24843dbb00>
base_url : http://192.168.1.41:9000
project : 8
public_key : 09b57f555e5041dea1a94bf410a0d7fd
secret_key : 2c79bbd6328946bbb0cba229587f7315
 
Sending a test message... DEBUG Sending message of length 3350 to http://192.168.1.41:9000/api/8/store/
Event ID was '4146e64156324f41aae698c5b7241bd6'

sentry4

错误捕捉

在Django中有两种方式可以捕捉到运行错误。
包裹app,捕捉其运行时向外抛出的错误

1
2
from raven.contrib.django.raven_compat.models import client
client.captureException()

 

logging

另外一种是修改logging配置,增加sentry的handler对不同等级的异常进行处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'sentry': {
'level': 'ERROR', # To capture more than ERROR, change to WARNING, INFO, etc.
'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
'tags': { 'custom-tag': 'x'},
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'root': {
'level': 'WARNING',
'handlers': [ 'sentry'],
},
'django.db.backends': {
'level': 'ERROR',
'handlers': [ 'console'],
'propagate': False,
},
'raven': {
'level': 'DEBUG',
'handlers': [ 'console'],
'propagate': False,
},
'sentry.errors': {
'level': 'DEBUG',
'handlers': [ 'console'],
'propagate': False,
},
},
}

 

web钩子

使用钩子可以简单的集成到已有的系统中,只需要构造一个POST请求
使用curl提交一个请求

1
2
3
4
curl http://192.168.1.41:9000/api/hooks/release/ builtin/8/d66807c921189783eb37158857e1fe5e4c77678db5332331430835afd3c58dd3/ \
-X POST \
-H 'Content-Type: application/json' \
-d '{"version": "abcdefg"}'

 

sentry5

 

猜你喜欢

转载自hugoren.iteye.com/blog/2383029