Thursday, July 13, 2017

Download Sentry Events via RESTful API

For those users who use Sentry as a error recording service. When you got an error issue, and wanting to know all events detail. But on Sentry web interface, you can read an event each time. And, of course, you wouldn't like the idea of copying each event til it ends. Fortunately, Sentry provided a web API for users who analysis data on their Sentry server. You may refer to Sentry API Docs for more detail.

After some time to explore, I understand that you need to create an access token on your sentry server http://your-host/api/. And after you are done, you are ready to access the APIs listed on the above document. And here is a simple example I used to retrieve all events of an issue and make some analysis.

import json, re, requests, sys

def main(host, issueId, token):
  endpoint = "http://%s/api/0/issues/%s/events/" % (host, issueId)
  headers = {"Authorization": "Bearer " + token}
  with open("data/%s.json" % issueId, "w") as f:
    f.write("[")
    nextLink = endpoint
    while (nextLink != None):
      if nextLink != endpoint :
        f.write(",")
      response = requests.get(nextLink, headers=headers)
      text = response.text[1:-1]
      f.write(text)
      headerLink = response.headers.get("link", "")
      regSearch = re.search("<([^<]*)>; rel=\"next\"; results=\"(true|false)\";", headerLink)
      if len(regSearch.groups()) >= 2 and regSearch.group(2) == "true":
        nextLink = regSearch.group(1)
      else:
        nextLink = None
    f.write("]")

In the above code, I uses Python requests to send requests to the sentry server. And I apply the regular expression to extract the next link of this page. I guess this shall be a simple one, and now you are ready to get your hands on the massive error logs.

No comments:

Post a Comment