-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDotNetExample.cs
More file actions
684 lines (586 loc) · 21.7 KB
/
DotNetExample.cs
File metadata and controls
684 lines (586 loc) · 21.7 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
/**
* Bugsink/Sentry SDK Integration Example for C# / .NET
* =====================================================
*
* This example demonstrates comprehensive error tracking integration
* using the Sentry SDK with a self-hosted Bugsink server.
*
* NuGet Packages:
* dotnet add package Sentry
* dotnet add package Sentry.AspNetCore
* dotnet add package Sentry.Extensions.Logging
*
* DSN Format:
* https://<project-key>@<your-bugsink-host>/<project-id>
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Sentry;
using Sentry.Protocol;
namespace BugsinkExample
{
// =============================================================================
// CONFIGURATION
// =============================================================================
public static class SentryConfig
{
public static string Dsn =>
Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "https://your-project-key@errors.observability.app.bauer-group.com/1";
public static string Environment =>
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
?? "development";
public static string Release =>
Environment.GetEnvironmentVariable("APP_VERSION") ?? "1.0.0";
}
// =============================================================================
// SENTRY SERVICE
// =============================================================================
/// <summary>
/// Singleton service for Sentry operations.
/// Provides comprehensive error tracking and performance monitoring.
/// </summary>
public sealed class SentryService : IDisposable
{
private static readonly Lazy<SentryService> _instance =
new Lazy<SentryService>(() => new SentryService());
private IDisposable? _sentryDisposable;
private bool _initialized = false;
private SentryService() { }
public static SentryService Instance => _instance.Value;
/// <summary>
/// Initialize Sentry SDK.
/// Call this once at application startup.
/// </summary>
public void Init()
{
if (_initialized)
{
Console.WriteLine("Sentry already initialized");
return;
}
_sentryDisposable = SentrySdk.Init(options =>
{
options.Dsn = SentryConfig.Dsn;
options.Environment = SentryConfig.Environment;
options.Release = $"my-app@{SentryConfig.Release}";
// Performance Monitoring
options.TracesSampleRate = SentryConfig.Environment == "production" ? 0.1 : 1.0;
options.ProfilesSampleRate = 0.1;
// Error Sampling
options.SampleRate = 1.0f;
// Data Handling
options.SendDefaultPii = false;
options.MaxBreadcrumbs = 50;
options.AttachStacktrace = true;
// Before Send Hook
options.SetBeforeSend(BeforeSendHandler);
// Before Breadcrumb Hook
options.SetBeforeBreadcrumb(BeforeBreadcrumbHandler);
// Debug mode
options.Debug = SentryConfig.Environment == "development";
});
// Set global tags
SentrySdk.ConfigureScope(scope =>
{
scope.SetTag("app.component", "backend");
scope.SetTag("app.runtime", "dotnet");
scope.SetTag("app.version", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
});
_initialized = true;
Console.WriteLine($"Sentry initialized for environment: {SentryConfig.Environment}");
}
/// <summary>
/// Process events before sending.
/// </summary>
private static SentryEvent? BeforeSendHandler(SentryEvent sentryEvent, Hint hint)
{
// Sanitize sensitive headers
if (sentryEvent.Request?.Headers != null)
{
var sensitiveHeaders = new[] { "Authorization", "Cookie", "X-API-Key" };
foreach (var header in sensitiveHeaders)
{
if (sentryEvent.Request.Headers.ContainsKey(header))
{
sentryEvent.Request.Headers[header] = "[REDACTED]";
}
}
}
// Filter specific exceptions
if (hint.Exception is ExpectedBusinessException)
{
return null; // Don't send this event
}
return sentryEvent;
}
/// <summary>
/// Process breadcrumbs before adding.
/// </summary>
private static Breadcrumb? BeforeBreadcrumbHandler(Breadcrumb breadcrumb, Hint hint)
{
// Filter health check requests
if (breadcrumb.Category == "http" &&
breadcrumb.Data?.TryGetValue("url", out var url) == true &&
url?.ToString()?.Contains("/health") == true)
{
return null;
}
return breadcrumb;
}
/// <summary>
/// Set user context.
/// </summary>
public void SetUser(string userId, string? email = null, string? username = null,
string? ipAddress = null, Dictionary<string, string>? additionalData = null)
{
SentrySdk.ConfigureScope(scope =>
{
scope.User = new SentryUser
{
Id = userId,
Email = email,
Username = username,
IpAddress = ipAddress,
Other = additionalData ?? new Dictionary<string, string>()
};
});
}
/// <summary>
/// Clear user context.
/// </summary>
public void ClearUser()
{
SentrySdk.ConfigureScope(scope => scope.User = null);
}
/// <summary>
/// Add a breadcrumb.
/// </summary>
public void AddBreadcrumb(string message, string? category = null,
BreadcrumbLevel level = BreadcrumbLevel.Info,
Dictionary<string, string>? data = null)
{
SentrySdk.AddBreadcrumb(
message: message,
category: category ?? "custom",
level: level,
data: data
);
}
/// <summary>
/// Set a tag.
/// </summary>
public void SetTag(string key, string value)
{
SentrySdk.ConfigureScope(scope => scope.SetTag(key, value));
}
/// <summary>
/// Set extra context.
/// </summary>
public void SetExtra(string key, object value)
{
SentrySdk.ConfigureScope(scope => scope.SetExtra(key, value));
}
/// <summary>
/// Set custom context.
/// </summary>
public void SetContext(string name, Dictionary<string, object> context)
{
SentrySdk.ConfigureScope(scope => scope.Contexts[name] = context);
}
/// <summary>
/// Capture an exception.
/// </summary>
public SentryId CaptureException(Exception exception)
{
return SentrySdk.CaptureException(exception);
}
/// <summary>
/// Capture an exception with extra context.
/// </summary>
public SentryId CaptureException(Exception exception, Dictionary<string, object>? extraContext)
{
SentrySdk.ConfigureScope(scope =>
{
if (extraContext != null)
{
foreach (var kvp in extraContext)
{
scope.SetExtra(kvp.Key, kvp.Value);
}
}
});
return SentrySdk.CaptureException(exception);
}
/// <summary>
/// Capture a message.
/// </summary>
public SentryId CaptureMessage(string message, SentryLevel level = SentryLevel.Info)
{
return SentrySdk.CaptureMessage(message, level);
}
/// <summary>
/// Capture a message with extra context.
/// </summary>
public SentryId CaptureMessage(string message, SentryLevel level,
Dictionary<string, object>? extraContext)
{
SentrySdk.ConfigureScope(scope =>
{
if (extraContext != null)
{
foreach (var kvp in extraContext)
{
scope.SetExtra(kvp.Key, kvp.Value);
}
}
});
return SentrySdk.CaptureMessage(message, level);
}
/// <summary>
/// Execute a callback within a transaction.
/// </summary>
public T WithTransaction<T>(string name, string operation, Func<ITransactionTracer, T> callback)
{
var transaction = SentrySdk.StartTransaction(name, operation);
SentrySdk.ConfigureScope(scope => scope.Transaction = transaction);
try
{
var result = callback(transaction);
transaction.Status = SpanStatus.Ok;
return result;
}
catch (Exception)
{
transaction.Status = SpanStatus.InternalError;
throw;
}
finally
{
transaction.Finish();
}
}
/// <summary>
/// Execute an async callback within a transaction.
/// </summary>
public async Task<T> WithTransactionAsync<T>(string name, string operation,
Func<ITransactionTracer, Task<T>> callback)
{
var transaction = SentrySdk.StartTransaction(name, operation);
SentrySdk.ConfigureScope(scope => scope.Transaction = transaction);
try
{
var result = await callback(transaction);
transaction.Status = SpanStatus.Ok;
return result;
}
catch (Exception)
{
transaction.Status = SpanStatus.InternalError;
throw;
}
finally
{
transaction.Finish();
}
}
/// <summary>
/// Flush pending events.
/// </summary>
public async Task FlushAsync(TimeSpan timeout)
{
await SentrySdk.FlushAsync(timeout);
}
public void Dispose()
{
_sentryDisposable?.Dispose();
}
}
// =============================================================================
// CUSTOM EXCEPTIONS
// =============================================================================
public class ExpectedBusinessException : Exception
{
public ExpectedBusinessException(string message) : base(message) { }
}
// =============================================================================
// EXAMPLE SERVICE
// =============================================================================
/// <summary>
/// Example service demonstrating Sentry integration patterns.
/// </summary>
public class ExampleService
{
private readonly SentryService _sentry;
public ExampleService()
{
_sentry = SentryService.Instance;
}
/// <summary>
/// Example method with error tracking.
/// </summary>
public string FetchData(string id)
{
_sentry.AddBreadcrumb($"Fetching data for {id}", "service",
data: new Dictionary<string, string> { { "id", id } });
if (id == "error")
{
throw new InvalidOperationException("Failed to fetch data");
}
return $"Data for {id}";
}
/// <summary>
/// Example method with transaction tracking.
/// </summary>
public async Task<int> ProcessBatchAsync(string[] items)
{
return await _sentry.WithTransactionAsync("process_batch", "task", async transaction =>
{
int processed = 0;
foreach (var item in items)
{
var span = transaction.StartChild("task.item", $"process_{item}");
try
{
await Task.Delay(50); // Simulate work
processed++;
span.Status = SpanStatus.Ok;
}
catch (Exception)
{
span.Status = SpanStatus.InternalError;
throw;
}
finally
{
span.Finish();
}
}
return processed;
});
}
}
// =============================================================================
// ASP.NET CORE CONFIGURATION EXAMPLE
// =============================================================================
/*
// Program.cs for ASP.NET Core 6+
using Sentry.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Add Sentry
builder.WebHost.UseSentry(options =>
{
options.Dsn = "https://your-key@errors.observability.app.bauer-group.com/1";
options.Environment = builder.Environment.EnvironmentName;
options.Release = "my-app@1.0.0";
options.TracesSampleRate = builder.Environment.IsProduction() ? 0.1 : 1.0;
options.SendDefaultPii = false;
options.MaxBreadcrumbs = 50;
// Performance monitoring for all requests
options.EnableTracing = true;
// Before send hook
options.SetBeforeSend((sentryEvent, hint) =>
{
// Filter or modify events
return sentryEvent;
});
});
builder.Services.AddControllers();
var app = builder.Build();
// Sentry middleware should be early in the pipeline
app.UseSentryTracing();
app.UseRouting();
app.MapControllers();
app.Run();
// Example Controller
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IHub _sentryHub;
public UsersController(IHub sentryHub)
{
_sentryHub = sentryHub;
}
[HttpGet("{id}")]
public ActionResult<User> GetUser(string id)
{
_sentryHub.AddBreadcrumb($"Fetching user {id}");
// Set additional context
_sentryHub.ConfigureScope(scope =>
{
scope.SetTag("endpoint", "get_user");
scope.SetExtra("userId", id);
});
// Your logic here
return Ok(new { Id = id, Name = "Test User" });
}
[HttpPost]
public ActionResult<User> CreateUser([FromBody] CreateUserRequest request)
{
using var _ = _sentryHub.PushScope();
_sentryHub.ConfigureScope(scope =>
{
scope.SetTag("operation", "create_user");
});
try
{
// Your logic here
return Ok(new { Id = Guid.NewGuid().ToString(), Name = request.Name });
}
catch (Exception ex)
{
_sentryHub.CaptureException(ex);
return StatusCode(500, new { Error = ex.Message });
}
}
}
// Error handling middleware
public class SentryErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly IHub _hub;
public SentryErrorHandlingMiddleware(RequestDelegate next, IHub hub)
{
_next = next;
_hub = hub;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_hub.ConfigureScope(scope =>
{
scope.SetExtra("requestPath", context.Request.Path);
scope.SetExtra("requestMethod", context.Request.Method);
});
var eventId = _hub.CaptureException(ex);
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync(new
{
Error = ex.Message,
EventId = eventId.ToString()
});
}
}
}
*/
// =============================================================================
// MAIN EXAMPLE
// =============================================================================
public class Program
{
public static async Task Main(string[] args)
{
Console.WriteLine(new string('=', 60));
Console.WriteLine("Bugsink/Sentry C#/.NET SDK Integration Example");
Console.WriteLine(new string('=', 60));
// Initialize Sentry
var sentry = SentryService.Instance;
sentry.Init();
// Set user context
sentry.SetUser(
userId: "user-123",
email: "developer@example.com",
username: "developer",
additionalData: new Dictionary<string, string>
{
{ "subscriptionTier", "premium" }
}
);
// Add breadcrumbs
sentry.AddBreadcrumb("Application started", "app");
sentry.AddBreadcrumb("User authenticated", "auth");
// Example 1: Capture handled exception
Console.WriteLine("\n1. Capturing handled exception...");
try
{
var result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
var eventId = sentry.CaptureException(ex, new Dictionary<string, object>
{
{ "operation", "division" },
{ "numerator", 10 },
{ "denominator", 0 }
});
Console.WriteLine($" Exception captured: {eventId}");
}
// Example 2: Capture message
Console.WriteLine("\n2. Capturing info message...");
var messageId = sentry.CaptureMessage(
"User completed onboarding flow",
SentryLevel.Info,
new Dictionary<string, object>
{
{ "stepsCompleted", 5 },
{ "timeTakenSeconds", 120 }
}
);
Console.WriteLine($" Message captured: {messageId}");
// Example 3: Use example service
Console.WriteLine("\n3. Using example service...");
var service = new ExampleService();
try
{
var data = service.FetchData("123");
Console.WriteLine($" Data fetched: {data}");
}
catch (Exception)
{
Console.WriteLine(" Error handled");
}
// Example 4: Transaction with service
Console.WriteLine("\n4. Processing batch with transaction...");
var processed = await service.ProcessBatchAsync(new[] { "a", "b", "c" });
Console.WriteLine($" Processed {processed} items");
// Example 5: Scoped context
Console.WriteLine("\n5. Using scoped context...");
using (SentrySdk.PushScope())
{
SentrySdk.ConfigureScope(scope =>
{
scope.SetTag("feature", "new_checkout");
scope.SetExtra("cartItems", 3);
scope.SetExtra("totalAmount", 99.99);
});
SentrySdk.CaptureMessage("Checkout initiated", SentryLevel.Info);
}
Console.WriteLine(" Scoped message captured");
// Example 6: Manual transaction with spans
Console.WriteLine("\n6. Creating transaction with spans...");
sentry.WithTransaction("order_processing", "task", transaction =>
{
var fetchSpan = transaction.StartChild("db.query", "Fetch order");
Task.Delay(50).Wait();
fetchSpan.Status = SpanStatus.Ok;
fetchSpan.Finish();
var paymentSpan = transaction.StartChild("http.client", "Payment API");
Task.Delay(100).Wait();
paymentSpan.Status = SpanStatus.Ok;
paymentSpan.Finish();
var updateSpan = transaction.StartChild("db.query", "Update order status");
Task.Delay(50).Wait();
updateSpan.Status = SpanStatus.Ok;
updateSpan.Finish();
return true;
});
Console.WriteLine(" Transaction with spans recorded");
// Clean up
sentry.ClearUser();
Console.WriteLine("\n" + new string('=', 60));
Console.WriteLine("All examples completed!");
Console.WriteLine("Check your Bugsink dashboard");
Console.WriteLine(new string('=', 60));
// Flush events before exit
await sentry.FlushAsync(TimeSpan.FromSeconds(5));
}
}
}