Skip to content

Commit cb96afc

Browse files
authored
feat: Automatically determine release and environment (#871)
1 parent e873bdb commit cb96afc

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

sentry_sdk/client.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
disable_capture_event,
1313
format_timestamp,
1414
get_type_name,
15+
get_default_release,
16+
get_default_environment,
1517
handle_in_app,
1618
logger,
1719
)
@@ -62,10 +64,10 @@ def _get_options(*args, **kwargs):
6264
rv["dsn"] = os.environ.get("SENTRY_DSN")
6365

6466
if rv["release"] is None:
65-
rv["release"] = os.environ.get("SENTRY_RELEASE")
67+
rv["release"] = get_default_release()
6668

6769
if rv["environment"] is None:
68-
rv["environment"] = os.environ.get("SENTRY_ENVIRONMENT")
70+
rv["environment"] = get_default_environment(rv["release"])
6971

7072
if rv["server_name"] is None and hasattr(socket, "gethostname"):
7173
rv["server_name"] = socket.gethostname()

sentry_sdk/utils.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import sys
66
import threading
7+
import subprocess
78

89
from datetime import datetime
910

@@ -52,6 +53,57 @@ def _get_debug_hub():
5253
pass
5354

5455

56+
def get_default_release():
57+
# type: () -> Optional[str]
58+
"""Try to guess a default release."""
59+
release = os.environ.get("SENTRY_RELEASE")
60+
if release:
61+
return release
62+
63+
with open(os.path.devnull, "w+") as null:
64+
try:
65+
release = (
66+
subprocess.Popen(
67+
["git", "rev-parse", "--short", "HEAD"],
68+
stdout=subprocess.PIPE,
69+
stderr=null,
70+
stdin=null,
71+
)
72+
.communicate()[0]
73+
.strip()
74+
.decode("utf-8")
75+
)
76+
except (OSError, IOError):
77+
pass
78+
79+
if release:
80+
return release
81+
82+
for var in (
83+
"HEROKU_SLUG_COMMIT",
84+
"SOURCE_VERSION",
85+
"CODEBUILD_RESOLVED_SOURCE_VERSION",
86+
"CIRCLE_SHA1",
87+
"GAE_DEPLOYMENT_ID",
88+
):
89+
release = os.environ.get(var)
90+
if release:
91+
return release
92+
return None
93+
94+
95+
def get_default_environment(
96+
release=None, # type: Optional[str]
97+
):
98+
# type: (...) -> Optional[str]
99+
rv = os.environ.get("SENTRY_ENVIRONMENT")
100+
if rv:
101+
return rv
102+
if release is not None:
103+
return "production"
104+
return None
105+
106+
55107
class CaptureInternalException(object):
56108
__slots__ = ()
57109

0 commit comments

Comments
 (0)