-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJRLog.m
436 lines (385 loc) · 13.7 KB
/
JRLog.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
// JRLog.m semver:1.2
// Copyright (c) 2006-2013 Jonathan 'Wolf' Rentzsch: http://rentzsch.com
// Some rights reserved: http://opensource.org/licenses/mit
// https://github.com/rentzsch/JRLog
#import "JRLog.h"
#include <unistd.h>
#include <mach/mach_init.h>
#if JRLogOverrideNSLog
id self = nil;
#endif
#undef NSLog
//
// Statics
//
#pragma mark Statics
static JRLogLevel sDefaultJRLogLevel = JRLogLevel_Debug;
NSString *JRLogLevelNames[] = {
@"UNSET",
@"DEBUG",
@"INFO",
@"WARN",
@"ERROR",
@"ASSERT",
@"FATAL",
@"OFF"
};
//
// JRLogCall
//
@implementation JRLogCall
- (id)initWithLevel:(JRLogLevel)callerLevel_
instance:(NSString*)instance_
file:(const char*)file_
line:(unsigned)line_
function:(const char*)function_
message:(NSString*)message_
{
self = [super init];
if (self) {
callerLevel = callerLevel_;
instance = [instance_ retain];
file = file_;
line = line_;
function = function_;
message = [message_ retain];
}
return self;
}
- (void)dealloc {
[instance release];
[message release];
[formattedMessage release];
[super dealloc];
}
- (void)setFormattedMessage:(NSString*)formattedMessage_ {
if (formattedMessage != formattedMessage_) {
[formattedMessage release];
formattedMessage = [formattedMessage_ retain];
}
}
@end
//
// JRLogDefaultLogger
//
@protocol JRLogDestinationDO
- (oneway void)logWithDictionary:(bycopy NSDictionary*)dictionary_;
@end
@interface JRLogDefaultLogger : NSObject <JRLogLogger> {
NSString *sessionUUID;
BOOL tryDO;
id<JRLogDestinationDO> destination;
}
+ (id)sharedLogger;
- (void)destinationDOAvailable:(NSNotification*)notification_;
@end
@implementation JRLogDefaultLogger
+ (id)sharedLogger {
static JRLogDefaultLogger *output = nil;
if (!output) {
output = [[JRLogDefaultLogger alloc] init];
}
return output;
}
- (id)init {
self = [super init];
if (self) {
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
#if TARGET_OS_IPHONE
sessionUUID = (id)CFUUIDCreateString(kCFAllocatorDefault, uuid);
tryDO = NO;
#else
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
sessionUUID = (id)CFUUIDCreateString(kCFAllocatorDefault, uuid);
#else
sessionUUID = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, uuid));
#endif
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:@selector(destinationDOAvailable:)
name:@"JRLogDestinationDOAvailable"
object:nil];
tryDO = YES;
#endif
CFRelease(uuid);
}
return self;
}
- (void)destinationDOAvailable:(NSNotification*)notification_ {
tryDO = YES;
}
- (void)logWithCall:(JRLogCall*)call_ {
if (tryDO) {
tryDO = NO;
#if !TARGET_OS_IPHONE
destination = (id)[[NSConnection rootProxyForConnectionWithRegisteredName:@"JRLogDestinationDO" host:nil] retain];
#endif
}
if (destination) {
NS_DURING
[destination logWithDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
[[NSBundle mainBundle] bundleIdentifier], @"bundleID",
sessionUUID, @"sessionUUID",
[NSNumber numberWithLong:getpid()], @"pid",
[NSDate date], @"date",
[NSNumber numberWithInt:call_->callerLevel], @"level",
call_->instance, @"instance",
[NSString stringWithUTF8String:call_->file], @"file",
[NSNumber numberWithUnsignedInt:call_->line], @"line",
[NSString stringWithUTF8String:call_->function], @"function",
call_->message, @"message",
nil]];
NS_HANDLER
if ([[localException name] isEqualToString:NSObjectInaccessibleException]) {
destination = nil;
} else {
[localException raise];
}
NS_ENDHANDLER
} else {
NSString *formattedMessage = [JRLogGetFormatter() formattedMessageWithCall:call_];
if (formattedMessage) {
puts([formattedMessage UTF8String]);
}
}
}
@end
//
// JRLogDefaultFormatter
//
@implementation JRLogDefaultFormatter
+ (id)sharedFormatter {
static JRLogDefaultFormatter *formatter = nil;
if (!formatter) {
formatter = [[JRLogDefaultFormatter alloc] init];
}
return formatter;
}
- (id)init {
self = [super init];
if (self) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
}
return self;
}
- (void)dealloc {
[dateFormatter release];
[super dealloc];
}
- (NSString*)formattedMessageWithCall:(JRLogCall*)call_ {
// "yyy-MM-dd HH:mm:ss.S MyProcess[PID:TASK] INFO MyClass.m:123: blah blah"
NSString *threadID = [NSString stringWithFormat:@"%x", mach_thread_self()];
return [NSString stringWithFormat:@"%@ %@[%d:%@] %@ %@:%u: %@",
[dateFormatter stringFromDate:[NSDate date]],
[[NSProcessInfo processInfo] processName],
getpid(),
threadID,
JRLogLevelNames[call_->callerLevel],
[[NSString stringWithUTF8String:call_->file] lastPathComponent],
call_->line,
call_->message];
}
@end
//
//
//
static JRLogLevel parseJRLogLevel(NSString *level_) {
static NSDictionary *levelLookup = nil;
if (!levelLookup) {
levelLookup = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:JRLogLevel_Debug], @"debug",
[NSNumber numberWithInt:JRLogLevel_Info], @"info",
[NSNumber numberWithInt:JRLogLevel_Warn], @"warn",
[NSNumber numberWithInt:JRLogLevel_Error], @"error",
[NSNumber numberWithInt:JRLogLevel_Assert], @"assert",
[NSNumber numberWithInt:JRLogLevel_Fatal], @"fatal",
[NSNumber numberWithInt:JRLogLevel_Off], @"off",
nil];
}
NSNumber *result = [levelLookup objectForKey:[level_ lowercaseString]];
return result ? [result intValue] : JRLogLevel_UNSET;
}
static void LoadJRLogSettings() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Load+interpret the Info.plist-based settings.
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
[settings addEntriesFromDictionary:[[NSBundle mainBundle] infoDictionary]];
[settings addEntriesFromDictionary:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
NSArray *keys = [settings allKeys];
unsigned keyIndex = 0, keyCount = (unsigned)[keys count];
for(; keyIndex < keyCount; keyIndex++) {
NSString *key = [keys objectAtIndex:keyIndex];
if ([key hasPrefix:@"JRLogLevel"]) {
JRLogLevel level = parseJRLogLevel([settings objectForKey:key]);
if (JRLogLevel_UNSET == level) {
NSLog(@"JRLog: can't parse \"%@\" JRLogLevel value for key \"%@\"", [settings objectForKey:key], key);
} else {
NSArray *keyNames = [key componentsSeparatedByString:@"."];
if ([keyNames count] == 2) {
// It's a pseudo-keypath: JRLogLevel.MyClassName.
Class c = NSClassFromString([keyNames lastObject]);
if (c) {
JRLogSetClassLevel(c, level);
} else {
NSLog(@"JRLog: unknown class \"%@\"", [keyNames lastObject]);
}
} else {
// Just a plain "JRLogLevel": it's for the default level.
JRLogSetDefaultLevel(level);
}
}
}
}
[pool release];
}
BOOL JRLogIsLevelActive(id self_, JRLogLevel callerLevel_) {
assert(callerLevel_ >= JRLogLevel_Debug && callerLevel_ <= JRLogLevel_Fatal);
static BOOL loadedJRLogSettings = NO;
if (!loadedJRLogSettings) {
loadedJRLogSettings = YES;
LoadJRLogSettings();
}
// Setting the default level to OFF disables all logging, regardless of everything else.
if (JRLogLevel_Off == sDefaultJRLogLevel)
return NO;
JRLogLevel currentLevel;
if (self_) {
currentLevel = JRLogGetClassLevel([self_ class]);
if (JRLogLevel_UNSET == currentLevel) {
currentLevel = sDefaultJRLogLevel;
}
} else {
currentLevel = sDefaultJRLogLevel;
// TODO It would be cool if we could use the file's name was a symbol to set logging levels for JRCLog... functions.
}
return callerLevel_ >= currentLevel;
}
void
JRLog(
id self_,
JRLogLevel callerLevel_,
unsigned line_,
const char *file_,
const char *function_,
NSString *format_,
...)
{
assert(callerLevel_ >= JRLogLevel_Debug && callerLevel_ <= JRLogLevel_Fatal);
assert(file_);
assert(function_);
assert(format_);
//
va_list args;
va_start(args, format_);
NSString *message = [[[NSString alloc] initWithFormat:format_ arguments:args] autorelease];
va_end(args);
id<JRLogLogger> logger = JRLogGetLogger();
JRLogCall *call = [[[JRLogCall alloc] initWithLevel:callerLevel_
instance:self_ ? [NSString stringWithFormat:@"<%@: %p>", [self_ class], self_] : @"nil"
file:file_
line:line_
function:function_
message:message] autorelease];
[logger logWithCall:call];
if (JRLogLevel_Fatal == callerLevel_) {
exit(1);
}
}
void
JRLogAssertionFailure(
id self_,
unsigned line_,
const char *file_,
const char *function_,
const char *condition_,
NSString *format_,
...)
{
assert(file_);
assert(function_);
assert(condition_);
NSString *message;
if (format_) {
va_list args;
va_start(args, format_);
message = [[[NSString alloc] initWithFormat:format_ arguments:args] autorelease];
va_end(args);
message = [NSString stringWithFormat:@"%s (%@)", condition_, message];
} else {
message = [NSString stringWithUTF8String:condition_];
}
id<JRLogLogger> logger = JRLogGetLogger();
JRLogCall *call = [[[JRLogCall alloc] initWithLevel:JRLogLevel_Assert
instance:self_ ? [NSString stringWithFormat:@"<%@: %p>", [self_ class], self_] : @"nil"
file:file_
line:line_
function:function_
message:message] autorelease];
[logger logWithCall:call];
// This is just here so "Stop on Objective-C Exception" will catch assertion failures.
NS_DURING
[NSException raise:@"JRLogAssertionFailure" format:@""];
NS_HANDLER
NS_ENDHANDLER
}
JRLogLevel JRLogGetDefaultLevel() {
return sDefaultJRLogLevel;
}
void JRLogSetDefaultLevel(JRLogLevel level_) {
assert(level_ >= JRLogLevel_Debug && level_ <= JRLogLevel_Off);
sDefaultJRLogLevel = level_;
}
NSMutableDictionary* classLoggingLevels() {
static NSMutableDictionary *sClassLoggingLevels = NULL;
if (!sClassLoggingLevels) {
sClassLoggingLevels = [[NSMutableDictionary alloc] initWithCapacity:64];
}
return sClassLoggingLevels;
}
JRLogLevel JRLogGetClassLevel(Class class_) {
NSNumber *value = [classLoggingLevels() objectForKey:class_];
if (value) {
return [value intValue];
} else {
Class superclass = [class_ superclass];
return superclass ? JRLogGetClassLevel(superclass) : JRLogLevel_UNSET;
}
}
void JRLogSetClassLevel(Class class_, JRLogLevel level_) {
if (JRLogLevel_UNSET == level_) {
[classLoggingLevels() removeObjectForKey:class_];
} else {
// Can't use
// [classLoggingLevels() setObject:[NSNumber numberWithInt:level_] forKey:class_];
// since -[NSMutableDictionary setObject:forKey:] is documented as copying its
// key (NSCopying) and Class doesn't support that protocol. So we use
// CFDictionarySetValue() which doesn't copy the key. See
// http://www.cocoabuilder.com/archive/cocoa/167178-objects-as-keys-nsmutabledictionary.html
// for background info.
CFDictionarySetValue((CFMutableDictionaryRef)classLoggingLevels(),
(const void*)class_,
(const void*)[NSNumber numberWithInt:level_]);
}
}
static id<JRLogLogger> sLogger = nil;
id<JRLogLogger> JRLogGetLogger() {
return sLogger ? sLogger : [JRLogDefaultLogger sharedLogger];
}
void JRLogSetLogger(id<JRLogLogger> logger_) {
if (sLogger != logger_) {
[(id)sLogger release];
sLogger = [(id)logger_ retain];
}
}
static id<JRLogFormatter> sFormatter = nil;
id<JRLogFormatter> JRLogGetFormatter() {
return sFormatter ? sFormatter : [JRLogDefaultFormatter sharedFormatter];
}
void JRLogSetFormatter(id<JRLogFormatter> formatter_) {
if (sFormatter != formatter_) {
[(id)sFormatter release];
sFormatter = [(id)formatter_ retain];
}
}