Skip to content

Commit 41e67c2

Browse files
feat(metrics): Trace-connected Metrics (Samples) (#4841)
Co-authored-by: Sentry Github Bot <[email protected]>
1 parent 40a1635 commit 41e67c2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

samples/Sentry.Samples.Console.Basic/Program.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
* For more advanced features of the SDK, see Sentry.Samples.Console.Customized.
1010
*/
1111

12+
using System.Diagnostics;
13+
using System.Net;
1214
using System.Net.Http;
1315
using static System.Console;
1416

@@ -50,6 +52,17 @@
5052
// Drop logs with level Info
5153
return log.Level is SentryLogLevel.Info ? null : log;
5254
});
55+
56+
// Sentry (trace-connected) Metrics via SentrySdk.Experimental.Metrics are enabled by default.
57+
options.Experimental.SetBeforeSendMetric<int>(static metric =>
58+
{
59+
// A demonstration of how you can modify the metric object before sending it to Sentry
60+
metric.SetAttribute("operating_system.platform", Environment.OSVersion.Platform.ToString());
61+
metric.SetAttribute("operating_system.version", Environment.OSVersion.Version.ToString());
62+
63+
// Return null to drop the metric
64+
return metric;
65+
});
5366
});
5467

5568
// This starts a new transaction and attaches it to the scope.
@@ -71,9 +84,22 @@ async Task FirstFunction()
7184
// This is an example of making an HttpRequest. A trace us automatically captured by Sentry for this.
7285
var messageHandler = new SentryHttpMessageHandler();
7386
var httpClient = new HttpClient(messageHandler, true);
87+
88+
var stopwatch = Stopwatch.StartNew();
7489
var html = await httpClient.GetStringAsync("https://example.com/");
90+
stopwatch.Stop();
91+
7592
WriteLine(html);
93+
94+
// Info-Log filtered via "BeforeSendLog" callback
7695
SentrySdk.Logger.LogInfo("HTTP Request completed.");
96+
97+
// Metric modified via "BeforeSendMetric" callback for type "int" before sending it to Sentry
98+
SentrySdk.Experimental.Metrics.EmitCounter("sentry.samples.console.basic.http_requests_completed", 1);
99+
100+
// Metric sent as is because no "BeforeSendMetric" is set for type "double"
101+
SentrySdk.Experimental.Metrics.EmitDistribution("sentry.samples.console.basic.http_request_duration", stopwatch.Elapsed.TotalSeconds, SentryUnits.Duration.Second,
102+
[new KeyValuePair<string, object>("http.request.method", HttpMethod.Get.Method), new KeyValuePair<string, object>("http.response.status_code", (int)HttpStatusCode.OK)]);
77103
}
78104

79105
async Task SecondFunction()

0 commit comments

Comments
 (0)