LoginSignup
7
2

More than 3 years have passed since last update.

Sentryのissue一覧をcsv形式でexportする

Last updated at Posted at 2020-09-02

概要

Sentryのissue一覧をAPIで取得し、csvファイルに変換する方法について紹介します。

Sentryの画面上にはissueを一括でダウンロードするような機能がなく、
issueの詳細を確認するためにはissue毎に毎回詳細画面を開かなくてはなりませんが、
Sentry APIを使用することにより、JSON形式で一覧データを取得することが可能です。

Sentry API

公式のAPI Referenceはこちらです。
https://docs.sentry.io/api/

issue一覧取得エンドポイントの他に、event一覧、詳細を取得するエンドポイントやステータス更新用エンドポイント等も用意されているようです。

issue一覧取得エンドポイント

URL

GET /api/0/projects/{organization_slug}/{project_slug}/issues/

Query parameter

key value description
statsPeriod "24h", "14d", or "" 対象期間
shortIdLookup 有効にする場合: 1 このパラメータを有効にし、shortId(issue毎のid)をqueryに含めるとshortIdで検索が可能になります
query "is:unresolved"event.timestamp:など その他の検索条件

※queryに指定できるパラメータは以下を参照してください。
https://docs.sentry.io/product/sentry-basics/search/#issue-properties

API Reference
https://docs.sentry.io/api/events/get-project-group-index/

issues一覧をcsv形式でエクスポートする

指定期間内のissue一覧の指定項目をcsv形式で./data/ディレクトリにエクスポートします。

手順

以下の手順に沿って実行してください。
1. 事前にAuth Tokenを作成します
 https://sentry.io/settings/account/api/auth-tokens/
2. 以下のpythonプログラムと同階層に data ディレクトリを作成してください
3. paramsのパラメータを必要に応じて修正してください
4. 以下のコマンドでプログラムを実行します
 $ python download_sentry_data.py <org>/<project> <auth_token>
5. csvファイルがdataディレクトリに生成されます

pythonサンプルプログラム

download_sentry_data.py

"""Download sentry data.
usage:
 1. create auth token (https://sentry.io/settings/account/api/auth-tokens/).
 2. make a directory for export if not exists.
    $ mkdir data
 3. fix event.timestamp (L27).
 4. execute
    $ python download_sentry_data.py <org>/<project> <auth_token>
 5. a CSV file with a name formatted as "./data/issues_YYYYmmDDHHMMSS.csv" is created.
"""

import requests
import csv
import sys
import datetime


if __name__ == '__main__':
    dt_now = datetime.datetime.now()
    now = dt_now.strftime('%Y%m%d%H%M%S')
    with open('./data/issues_{0}.csv'.format(now), 'w', encoding='utf-8') as csvfile:
        fieldnames = ['count', 'title', 'status', 'lastSeen', 'firstSeen', 'culprit', 'permalink']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore')
        writer.writeheader()
        url = f'https://app.getsentry.com/api/0/projects/{sys.argv[1]}/issues/'
        # time-range absolute date
        params = {'query': 'event.timestamp:>=2020-08-01T00:00:00 event.timestamp:<2020-09-01T00:00:00'}
        while True:
            response = requests.get(
                url,
                params=params,
                headers={'Authorization': 'Bearer {TOKEN}'.format(TOKEN=sys.argv[2])}
                )
            data = response.json()
            for event in data:
                # tags = {item['key']: item['value'] for item in event['tags']}
                writer.writerow(dict(event))
            link = response.headers.get('Link')
            print(f"Last event date: {data[-1]['lastSeen']}")
            if link and 'rel="next"; results="true"' in link:
                print("Getting next page...")
                url = link.split()[4][1:-2]
            else:
                break

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2