This repository has been archived by the owner on Aug 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
RavenClient.m
449 lines (370 loc) · 17.3 KB
/
RavenClient.m
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
//
// RavenClient.m
// Raven
//
// Created by Kevin Renskers on 25-05-12.
// Copyright (c) 2012 Gangverk. All rights reserved.
//
#import <sys/utsname.h>
#import "RavenClient.h"
#import "RavenClient_Private.h"
#import "RavenConfig.h"
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif
NSString *const kRavenLogLevelArray[] = {
@"debug",
@"info",
@"warning",
@"error",
@"fatal"
};
NSString *const userDefaultsKey = @"nl.mixedCase.RavenClient.Exceptions";
NSString *const sentryProtocol = @"7";
NSString *const sentryClient = @"raven-objc/0.5.0";
static RavenClient *sharedClient = nil;
@implementation RavenClient {
NSString *_release;
}
void exceptionHandler(NSException *exception) {
[[RavenClient sharedClient] captureException:exception sendNow:NO];
}
#pragma mark - Setters and getters
- (NSDateFormatter *)dateFormatter {
if (!_dateFormatter) {
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setTimeZone:timeZone];
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
}
return _dateFormatter;
}
- (void)setRelease:(NSString *)newRelease {
_release = newRelease;
}
- (void)setTags:(NSDictionary *)tags {
[self setTags:tags withDefaultValues:YES];
}
- (void)setTags:(NSDictionary *)tags withDefaultValues:(BOOL)withDefaultValues {
NSMutableDictionary *mTags = [[NSMutableDictionary alloc] initWithDictionary:tags];
if (withDefaultValues && ![mTags objectForKey:@"Build version"]) {
NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
if (buildVersion) {
[mTags setObject:buildVersion forKey:@"Build version"];
}
}
#if TARGET_OS_IPHONE
if (withDefaultValues && ![mTags objectForKey:@"OS version"]) {
NSString *osVersion = [[UIDevice currentDevice] systemVersion];
[mTags setObject:osVersion forKey:@"OS version"];
}
if (withDefaultValues && ![mTags objectForKey:@"Device model"]) {
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceModel = [NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];
[mTags setObject:deviceModel forKey:@"Device model"];
}
#endif
_tags = mTags;
}
#pragma mark - Singleton and initializers
+ (RavenClient *)clientWithDSN:(NSString *)DSN {
return [[self alloc] initWithDSN:DSN];
}
+ (RavenClient *)clientWithDSN:(NSString *)DSN extra:(NSDictionary *)extra {
return [[self alloc] initWithDSN:DSN extra:extra];
}
+ (RavenClient *)clientWithDSN:(NSString *)DSN extra:(NSDictionary *)extra tags:(NSDictionary *)tags {
return [[self alloc] initWithDSN:DSN extra:extra tags:tags];
}
+ (RavenClient *)clientWithDSN:(NSString *)DSN extra:(NSDictionary *)extra tags:(NSDictionary *)tags logger:(NSString *)logger {
return [[self alloc] initWithDSN:DSN extra:extra tags:tags logger:logger];
}
+ (RavenClient *)sharedClient {
return sharedClient;
}
+ (void)setSharedClient:(RavenClient *)client {
sharedClient = client;
}
- (instancetype)initWithDSN:(NSString *)DSN {
return [self initWithDSN:DSN extra:@{}];
}
- (instancetype)initWithDSN:(NSString *)DSN extra:(NSDictionary *)extra {
return [self initWithDSN:DSN extra:extra tags:@{}];
}
- (instancetype)initWithDSN:(NSString *)DSN extra:(NSDictionary *)extra tags:(NSDictionary *)tags {
return [self initWithDSN:DSN extra:extra tags:tags logger:nil];
}
- (instancetype)initWithDSN:(NSString *)DSN extra:(NSDictionary *)extra tags:(NSDictionary *)tags logger:(NSString *)logger {
self = [super init];
if (self) {
if (DSN)
_config = [[RavenConfig alloc] init];
_extra = extra;
_logger = logger;
self.tags = tags;
// bind release
NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
if (buildVersion) {
_release = buildVersion;
}
// Parse DSN
if (_config && ![_config setDSN:DSN]) {
NSLog(@"Invalid DSN %@!", DSN);
return nil;
}
}
return self;
}
#pragma mark - Messages
- (void)captureMessage:(NSString *)message {
[self captureMessage:message level:kRavenLogLevelDebugInfo];
}
- (void)captureMessage:(NSString *)message level:(RavenLogLevel)level {
[self captureMessage:message level:level method:nil file:nil line:0];
}
- (void)captureMessage:(NSString *)message level:(RavenLogLevel)level method:(const char *)method file:(const char *)file line:(NSInteger)line {
[self captureMessage:message level:level additionalExtra:nil additionalTags:nil method:method file:file line:line];
}
- (void)captureMessage:(NSString *)message level:(RavenLogLevel)level additionalExtra:(NSDictionary *)additionalExtra additionalTags:(NSDictionary *)additionalTags {
[self captureMessage:message level:level additionalExtra:additionalExtra additionalTags:additionalTags method:nil file:nil line:0];
}
- (void)captureMessage:(NSString *)message
level:(RavenLogLevel)level
additionalExtra:(NSDictionary *)additionalExtra
additionalTags:(NSDictionary *)additionalTags
method:(const char *)method
file:(const char *)file
line:(NSInteger)line {
[self captureMessage:message level:level additionalExtra:additionalExtra additionalTags:additionalTags method:method file:file line:line sendNow:YES];
}
- (void)captureMessage:(NSString *)message
level:(RavenLogLevel)level
additionalExtra:(NSDictionary *)additionalExtra
additionalTags:(NSDictionary *)additionalTags
method:(const char *)method
file:(const char *)file
line:(NSInteger)line
sendNow:(BOOL)sendNow {
NSArray *stacktrace;
NSString *culprit;
if (method && file && line) {
NSString *filename = [[NSString stringWithUTF8String:file] lastPathComponent];
NSString *methodString = [NSString stringWithUTF8String:method];
NSDictionary *frame = [NSDictionary dictionaryWithObjectsAndKeys:
filename, @"filename",
methodString, @"function",
[NSNumber numberWithInteger:line], @"lineno",
nil];
stacktrace = [NSArray arrayWithObject:frame];
culprit = [NSString stringWithFormat:@"%@ / %@", filename, methodString];
}
[self captureMessage:message level:level additionalExtra:additionalExtra additionalTags:additionalTags stacktrace:stacktrace culprit:culprit sendNow:sendNow];
}
- (void)captureMessage:(NSString *)message
level:(RavenLogLevel)level
additionalExtra:(NSDictionary *)additionalExtra
additionalTags:(NSDictionary *)additionalTags
stacktrace:(NSArray *)stacktrace
culprit:(NSString *)culprit
sendNow:(BOOL)sendNow {
NSDictionary *data = [self prepareDictionaryForMessage:message
level:level
additionalExtra:additionalExtra
additionalTags:additionalTags
culprit:culprit
stacktrace:stacktrace
exception:nil];
if (!sendNow) {
// We can't send this message to Sentry now, e.g. because the error was network related and the user may not have a data connection So, save it into NSUserDefaults.
NSArray *reports = [[NSUserDefaults standardUserDefaults] objectForKey:userDefaultsKey];
if (reports != nil) {
NSMutableArray *reportsCopy = [reports mutableCopy];
[reportsCopy addObject:data];
[[NSUserDefaults standardUserDefaults] setObject:reportsCopy forKey:userDefaultsKey];
} else {
reports = [NSArray arrayWithObject:data];
[[NSUserDefaults standardUserDefaults] setObject:reports forKey:userDefaultsKey];
}
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[self sendDictionary:data];
}
}
#pragma mark - Exceptions
- (void)captureException:(NSException *)exception {
[self captureException:exception sendNow:YES];
}
- (void)captureException:(NSException *)exception sendNow:(BOOL)sendNow {
[self captureException:exception additionalExtra:nil additionalTags:nil sendNow:sendNow];
}
- (void)captureException:(NSException *)exception additionalExtra:(NSDictionary *)additionalExtra additionalTags:(NSDictionary *)additionalTags sendNow:(BOOL)sendNow {
NSString *message = [NSString stringWithFormat:@"%@: %@", exception.name, exception.reason];
NSDictionary *exceptionDict = [NSDictionary dictionaryWithObjectsAndKeys:
exception.name, @"type",
exception.reason, @"value",
nil];
NSArray *callStack = [exception callStackSymbols];
NSMutableArray *stacktrace = [[NSMutableArray alloc] initWithCapacity:[callStack count]];
for (NSString *call in callStack) {
[stacktrace addObject:[NSDictionary dictionaryWithObjectsAndKeys:call, @"function", nil]];
}
NSDictionary *data = [self prepareDictionaryForMessage:message
level:kRavenLogLevelDebugFatal
additionalExtra:additionalExtra
additionalTags:additionalTags
culprit:nil
stacktrace:stacktrace
exception:exceptionDict];
if (!sendNow) {
// We can't send this exception to Sentry now, e.g. because the app is killed before the
// connection can be made. So, save it into NSUserDefaults.
NSArray *reports = [[NSUserDefaults standardUserDefaults] objectForKey:userDefaultsKey];
if (reports != nil) {
NSMutableArray *reportsCopy = [reports mutableCopy];
[reportsCopy addObject:data];
[[NSUserDefaults standardUserDefaults] setObject:reportsCopy forKey:userDefaultsKey];
} else {
reports = [NSArray arrayWithObject:data];
[[NSUserDefaults standardUserDefaults] setObject:reports forKey:userDefaultsKey];
}
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[self sendDictionary:data];
}
}
- (void)captureException:(NSException *)exception method:(const char *)method file:(const char *)file line:(NSInteger)line sendNow:(BOOL)sendNow {
NSString *message = [NSString stringWithFormat:@"%@: %@", exception.name, exception.reason];
NSDictionary *exceptionDict = [NSDictionary dictionaryWithObjectsAndKeys:
exception.name, @"type",
exception.reason, @"value",
nil];
NSArray *callStack = [exception callStackSymbols];
NSMutableArray *stacktrace;
if (method && file && line) {
NSDictionary *frame = [NSDictionary dictionaryWithObjectsAndKeys:
[[NSString stringWithUTF8String:file] lastPathComponent], @"filename",
[NSString stringWithUTF8String:method], @"function",
[NSNumber numberWithInteger:line], @"lineno",
nil];
stacktrace = [NSMutableArray arrayWithObject:frame];
}
for (NSString *call in callStack) {
[stacktrace addObject:[NSDictionary dictionaryWithObjectsAndKeys:call, @"function", nil]];
}
NSDictionary *data = [self prepareDictionaryForMessage:message
level:kRavenLogLevelDebugFatal
additionalExtra:nil
additionalTags:nil
culprit:nil
stacktrace:stacktrace
exception:exceptionDict];
if (!sendNow) {
// We can't send this exception to Sentry now, e.g. because the app is killed before the
// connection can be made. So, save it into NSUserDefaults.
NSArray *reports = [[NSUserDefaults standardUserDefaults] objectForKey:userDefaultsKey];
if (reports != nil) {
NSMutableArray *reportsCopy = [reports mutableCopy];
[reportsCopy addObject:data];
[[NSUserDefaults standardUserDefaults] setObject:reportsCopy forKey:userDefaultsKey];
} else {
reports = [NSArray arrayWithObject:data];
[[NSUserDefaults standardUserDefaults] setObject:reports forKey:userDefaultsKey];
}
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[self sendDictionary:data];
}
}
- (void)setupExceptionHandler {
NSSetUncaughtExceptionHandler(&exceptionHandler);
// Process saved crash reports
NSArray *reports = [[NSUserDefaults standardUserDefaults] objectForKey:userDefaultsKey];
if (reports != nil && [reports count]) {
for (NSDictionary *data in reports) {
[self sendDictionary:data];
}
[[NSUserDefaults standardUserDefaults] setObject:[NSArray array] forKey:userDefaultsKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
#pragma mark - Private methods
- (NSString *)generateUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
NSString *res = [(__bridge NSString *)string stringByReplacingOccurrencesOfString:@"-" withString:@""];
CFRelease(string);
return res;
}
- (NSDictionary *)prepareDictionaryForMessage:(NSString *)message
level:(RavenLogLevel)level
additionalExtra:(NSDictionary *)additionalExtra
additionalTags:(NSDictionary *)additionalTags
culprit:(NSString *)culprit
stacktrace:(NSArray *)stacktrace
exception:(NSDictionary *)exceptionDict {
NSDictionary *stacktraceDict = [NSDictionary dictionaryWithObjectsAndKeys:stacktrace, @"frames", nil];
NSMutableDictionary *extra = [NSMutableDictionary dictionaryWithDictionary:self.extra];
if (additionalExtra.count) {
[extra addEntriesFromDictionary:additionalExtra];
}
NSMutableDictionary *tags = [NSMutableDictionary dictionaryWithDictionary:self.tags];
if (additionalTags.count) {
[tags addEntriesFromDictionary:additionalTags];
}
return [NSDictionary dictionaryWithObjectsAndKeys:
[self generateUUID], @"event_id",
self.config.projectId ?: @"", @"project",
[self.dateFormatter stringFromDate:[NSDate date]], @"timestamp",
kRavenLogLevelArray[level], @"level",
@"objc", @"platform",
self.user ?: @"", @"user",
extra, @"extra",
tags, @"tags",
self.logger ?: @"", @"logger",
_release ?: @"", @"release",
message, @"message",
culprit ?: @"", @"culprit",
stacktraceDict, @"stacktrace",
exceptionDict, @"exception",
nil];
}
- (void)sendDictionary:(NSDictionary *)dict {
NSData *JSON = [self encodeJSON:dict];
[self sendJSON:JSON];
}
- (void)sendJSON:(NSData *)JSON {
if (!self.config) {
NSLog(@"Sentry JSON (DSN not configured, will not be sent):\n%@\n",
[[NSString alloc] initWithData:JSON encoding:NSUTF8StringEncoding]);
return;
}
NSString *header = [NSString stringWithFormat:@"Sentry sentry_version=%@, sentry_client=%@, sentry_timestamp=%ld, sentry_key=%@, sentry_secret=%@",
sentryProtocol,
sentryClient,
(long)[NSDate timeIntervalSinceReferenceDate],
self.config.publicKey,
self.config.secretKey];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.config.serverURL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[JSON length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:JSON];
[request setValue:header forHTTPHeaderField:@"X-Sentry-Auth"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
NSLog(@"JSON sent to Sentry");
} else {
NSLog(@"Connection failed! Error - %@ %@", [connectionError localizedDescription], [[connectionError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
}];
}
#pragma mark - JSON helpers
- (NSData *)encodeJSON:(id)obj {
NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:nil];
return data;
}
@end