-
-
Notifications
You must be signed in to change notification settings - Fork 242
/
SentryTarget.cs
327 lines (278 loc) · 11.6 KB
/
SentryTarget.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Net;
using System.Threading;
using NLog;
using NLog.Common;
using NLog.Targets;
using NzbDrone.Common.EnvironmentInfo;
using Sentry;
namespace NzbDrone.Common.Instrumentation.Sentry
{
[Target("Sentry")]
public class SentryTarget : TargetWithLayout
{
// don't report uninformative SQLite exceptions
// busy/locked are benign https://forums.sonarr.tv/t/owin-sqlite-error-5-database-is-locked/5423/11
// The others will be user configuration problems and silt up Sentry
private static readonly HashSet<SQLiteErrorCode> FilteredSQLiteErrors = new HashSet<SQLiteErrorCode>
{
SQLiteErrorCode.Busy,
SQLiteErrorCode.Locked,
SQLiteErrorCode.Perm,
SQLiteErrorCode.ReadOnly,
SQLiteErrorCode.IoErr,
SQLiteErrorCode.Corrupt,
SQLiteErrorCode.Full,
SQLiteErrorCode.CantOpen,
SQLiteErrorCode.Auth
};
// use string and not Type so we don't need a reference to the project
// where these are defined
private static readonly HashSet<string> FilteredExceptionTypeNames = new HashSet<string>
{
// UnauthorizedAccessExceptions will just be user configuration issues
"UnauthorizedAccessException",
// Out Of Memory isn't very informative
"OutOfMemoryException",
// Filter out people stuck in boot loops
"CorruptDatabaseException"
};
public static readonly List<string> FilteredExceptionMessages = new List<string>
{
// Swallow the many, many exceptions flowing through from Jackett
"Jackett.Common.IndexerException",
// Fix openflixr being stupid with permissions
"openflixr"
};
// exception types in this list will additionally have the exception message added to the
// sentry fingerprint. Make sure that this message doesn't vary by exception
// (e.g. containing a path or a url) so that the sentry grouping is sensible
private static readonly HashSet<string> IncludeExceptionMessageTypes = new HashSet<string>
{
"SQLiteException"
};
private static readonly IDictionary<LogLevel, SentryLevel> LoggingLevelMap = new Dictionary<LogLevel, SentryLevel>
{
{ LogLevel.Debug, SentryLevel.Debug },
{ LogLevel.Error, SentryLevel.Error },
{ LogLevel.Fatal, SentryLevel.Fatal },
{ LogLevel.Info, SentryLevel.Info },
{ LogLevel.Trace, SentryLevel.Debug },
{ LogLevel.Warn, SentryLevel.Warning },
};
private static readonly IDictionary<LogLevel, BreadcrumbLevel> BreadcrumbLevelMap = new Dictionary<LogLevel, BreadcrumbLevel>
{
{ LogLevel.Debug, BreadcrumbLevel.Debug },
{ LogLevel.Error, BreadcrumbLevel.Error },
{ LogLevel.Fatal, BreadcrumbLevel.Critical },
{ LogLevel.Info, BreadcrumbLevel.Info },
{ LogLevel.Trace, BreadcrumbLevel.Debug },
{ LogLevel.Warn, BreadcrumbLevel.Warning },
};
private readonly DateTime _startTime = DateTime.UtcNow;
private readonly IDisposable _sdk;
private readonly SentryDebounce _debounce;
private bool _disposed;
private bool _unauthorized;
public bool FilterEvents { get; set; }
public bool SentryEnabled { get; set; }
public SentryTarget(string dsn)
{
_sdk = SentrySdk.Init(o =>
{
o.Dsn = dsn;
o.AttachStacktrace = true;
o.MaxBreadcrumbs = 200;
o.Release = $"{BuildInfo.AppName}@{BuildInfo.Release}";
o.BeforeSend = x => SentryCleanser.CleanseEvent(x);
o.BeforeBreadcrumb = x => SentryCleanser.CleanseBreadcrumb(x);
o.Environment = BuildInfo.Branch;
});
InitializeScope();
_debounce = new SentryDebounce();
// initialize to true and reconfigure later
// Otherwise it will default to false and any errors occurring
// before config file gets read will not be filtered
FilterEvents = true;
SentryEnabled = true;
}
public void InitializeScope()
{
SentrySdk.ConfigureScope(scope =>
{
scope.User = new User
{
Id = HashUtil.AnonymousToken()
};
scope.Contexts.App.Name = BuildInfo.AppName;
scope.Contexts.App.Version = BuildInfo.Version.ToString();
scope.Contexts.App.StartTime = _startTime;
scope.Contexts.App.Hash = HashUtil.AnonymousToken();
scope.Contexts.App.Build = BuildInfo.Release; // Git commit cache?
scope.SetTag("culture", Thread.CurrentThread.CurrentCulture.Name);
scope.SetTag("branch", BuildInfo.Branch);
scope.SetTag("runtime_identifier", System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier);
});
}
public void UpdateScope(IOsInfo osInfo)
{
SentrySdk.ConfigureScope(scope =>
{
scope.SetTag("is_docker", $"{osInfo.IsDocker}");
});
}
public void UpdateScope(Version databaseVersion, int migration, string updateBranch, IPlatformInfo platformInfo)
{
SentrySdk.ConfigureScope(scope =>
{
scope.Environment = updateBranch;
scope.SetTag("runtime_version", $"{PlatformInfo.PlatformName} {platformInfo.Version}");
if (databaseVersion != default(Version))
{
scope.SetTag("sqlite_version", $"{databaseVersion}");
scope.SetTag("database_migration", $"{migration}");
}
});
}
private void OnError(Exception ex)
{
var webException = ex as WebException;
if (webException != null)
{
var response = webException.Response as HttpWebResponse;
var statusCode = response?.StatusCode;
if (statusCode == HttpStatusCode.Unauthorized)
{
_unauthorized = true;
_debounce.Clear();
}
}
InternalLogger.Error(ex, "Unable to send error to Sentry");
}
private static List<string> GetFingerPrint(LogEventInfo logEvent)
{
if (logEvent.Properties.ContainsKey("Sentry"))
{
return ((string[])logEvent.Properties["Sentry"]).ToList();
}
var fingerPrint = new List<string>
{
logEvent.Level.ToString(),
logEvent.LoggerName,
logEvent.Message
};
var ex = logEvent.Exception;
if (ex != null)
{
fingerPrint.Add(ex.GetType().FullName);
if (ex.TargetSite != null)
{
fingerPrint.Add(ex.TargetSite.ToString());
}
if (ex.InnerException != null)
{
fingerPrint.Add(ex.InnerException.GetType().FullName);
}
else if (IncludeExceptionMessageTypes.Contains(ex.GetType().Name))
{
fingerPrint.Add(ex?.Message);
}
}
return fingerPrint;
}
public bool IsSentryMessage(LogEventInfo logEvent)
{
if (logEvent.Properties.ContainsKey("Sentry"))
{
return logEvent.Properties["Sentry"] != null;
}
if (logEvent.Level >= LogLevel.Error && logEvent.Exception != null)
{
if (FilterEvents)
{
var sqlEx = logEvent.Exception as SQLiteException;
if (sqlEx != null && FilteredSQLiteErrors.Contains(sqlEx.ResultCode))
{
return false;
}
if (FilteredExceptionTypeNames.Contains(logEvent.Exception.GetType().Name))
{
return false;
}
if (FilteredExceptionMessages.Any(x => logEvent.Exception.Message.Contains(x)))
{
return false;
}
}
return true;
}
return false;
}
protected override void Write(LogEventInfo logEvent)
{
if (_unauthorized || !SentryEnabled)
{
return;
}
try
{
SentrySdk.AddBreadcrumb(logEvent.FormattedMessage, logEvent.LoggerName, level: BreadcrumbLevelMap[logEvent.Level]);
// don't report non-critical events without exceptions
if (!IsSentryMessage(logEvent))
{
return;
}
var fingerPrint = GetFingerPrint(logEvent);
if (!_debounce.Allowed(fingerPrint))
{
return;
}
var extras = logEvent.Properties.ToDictionary(x => x.Key.ToString(), x => (object)x.Value.ToString());
extras.Remove("Sentry");
if (logEvent.Exception != null)
{
foreach (DictionaryEntry data in logEvent.Exception.Data)
{
extras.Add(data.Key.ToString(), data.Value.ToString());
}
}
var sentryEvent = new SentryEvent(logEvent.Exception)
{
Level = LoggingLevelMap[logEvent.Level],
Logger = logEvent.LoggerName,
Message = logEvent.FormattedMessage
};
sentryEvent.SetExtras(extras);
sentryEvent.SetFingerprint(fingerPrint);
SentrySdk.CaptureEvent(sentryEvent);
}
catch (Exception e)
{
OnError(e);
}
}
// https://stackoverflow.com/questions/2496311/implementing-idisposable-on-a-subclass-when-the-parent-also-implements-idisposab
protected override void Dispose(bool disposing)
{
// Only do something if we're not already disposed
if (_disposed)
{
// If disposing == true, we're being called from a call to base.Dispose(). In this case, we Dispose() our logger
// If we're being called from a finalizer, our logger will get finalized as well, so no need to do anything.
if (disposing)
{
_sdk?.Dispose();
}
// Flag us as disposed. This allows us to handle multiple calls to Dispose() as well as ObjectDisposedException
_disposed = true;
}
// This should always be safe to call multiple times!
// We could include it in the check for disposed above, but I left it out to demonstrate that it's safe
base.Dispose(disposing);
}
}
}