-
Notifications
You must be signed in to change notification settings - Fork 2
/
EcLogger.m
630 lines (572 loc) · 14.6 KB
/
EcLogger.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
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
/** Enterprise Control Configuration and Logging
Copyright (C) 2012 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <[email protected]>
Date: Febrary 2010
Originally developed from 1996 to 2012 by Brainstorm, and donated to
the FSF.
This file is part of the GNUstep project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02111 USA.
*/
#import <Foundation/Foundation.h>
#import <Foundation/NSDebug.h>
#import "EcProcess.h"
#import "EcLogger.h"
NSString* const EcLoggersDidChangeNotification
= @"EcLoggersDidChangeNotification";
@implementation EcLogger
static Class loggersClass;
static NSLock *loggersLock;
static NSMutableArray *loggers;
static NSArray *modes;
+ (void) initialize
{
if (self == [EcLogger class])
{
id objects[1];
loggersLock = [NSLock new];
loggers = [[NSMutableArray alloc] initWithCapacity: 6];
objects[0] = NSDefaultRunLoopMode;
modes = [[NSArray alloc] initWithObjects: objects count: 1];
[self setFactory: self];
}
}
+ (EcLogger*) loggerForType: (EcLogType)t
{
unsigned count;
EcLogger *logger;
[loggersLock lock];
count = [loggers count];
while (count-- > 0)
{
logger = [loggers objectAtIndex: count];
if (logger->type == t)
{
[loggersLock unlock];
return logger;
}
}
logger = [[loggersClass alloc] init];
if (logger != nil)
{
logger->lock = [NSRecursiveLock new];
logger->type = t;
logger->key = [cmdLogKey(t) copy];
logger->flushKey
= [[NSString alloc] initWithFormat: @"%@Flush", logger->key];
logger->serverKey
= [[NSString alloc] initWithFormat: @"%@Server", logger->key];
logger->interval = 10.0;
logger->size = 8 * 1024;
logger->message = [[NSMutableString alloc] initWithCapacity: 2048];
if (LT_ERROR == t || LT_AUDIT == t || LT_ALERT == t)
{
logger->shouldForward = YES;
}
[[NSNotificationCenter defaultCenter]
addObserver: logger
selector: @selector(update)
name: NSUserDefaultsDidChangeNotification
object: [EcProc cmdDefaults]];
[logger update];
[loggers addObject: logger];
RELEASE(logger);
}
[loggersLock unlock];
return logger;
}
+ (void) setFactory: (Class)c
{
NSMutableArray *old = nil;
if (Nil == c) c = [self class];
NSAssert([c isSubclassOfClass: self], NSInvalidArgumentException);
[loggersLock lock];
if (loggersClass != c)
{
old = loggers;
loggers = [NSMutableArray new];
loggersClass = c;
}
[loggersLock unlock];
if (nil != old)
{
[old makeObjectsPerformSelector: @selector(flush)];
[old release];
[[NSNotificationCenter defaultCenter] postNotificationName:
EcLoggersDidChangeNotification object: self];
}
}
/* Should only be called on main thread, but doesn't matter.
*/
- (oneway void) cmdGnip: (id <CmdPing>)from
sequence: (unsigned)num
extra: (NSData*)data
{
return;
}
/*
* When connecting to a logging server, we need to register so it
* knows who we are.
* Should only be called on main thread.
*/
- (void) cmdMadeConnectionToServer: (NSString*)name
{
id<CmdLogger> server;
server = (id<CmdLogger>)[EcProc server: name];
[server registerClient: self
identifier: [[NSProcessInfo processInfo] processIdentifier]
name: cmdLogName()
transient: NO];
}
/* Should only be called on main thread, but doesn't matter.
*/
- (oneway void) cmdPing: (id <CmdPing>)from
sequence: (unsigned)num
extra: (NSData*)data
{
[from cmdGnip: self sequence: num extra: nil];
}
/* Should only be called on main thread.
*/
- (oneway void) cmdQuit: (NSInteger)status
{
[EcProc cmdQuit: status];
}
- (void) dealloc
{
[self flush];
[timer invalidate];
[[NSNotificationCenter defaultCenter] removeObserver: self];
RELEASE(key);
RELEASE(flushKey);
RELEASE(serverKey);
RELEASE(serverName);
RELEASE(message);
RELEASE(lock);
[super dealloc];
}
- (NSString*) description
{
NSMutableString *s = [NSMutableString stringWithCapacity: 256];
[lock lock];
if (NO == shouldForward)
{
[s appendFormat: @"%@ output to file only.\n", key];
}
else if (size == 0)
{
[s appendFormat: @"%@ output is immediate.\n", key];
}
else if (interval > 0.0)
{
[s appendFormat: @"%@ flushed every %g seconds", key, interval];
[s appendFormat: @" or with a %u byte buffer.\n", size];
if (timer != nil)
{
[s appendFormat: @"Next flush - %@\n", [timer fireDate]];
}
}
else
{
[s appendFormat: @"%@ flushed with a %u byte buffer.\n", key, size];
}
[lock unlock];
return s;
}
- (BOOL) ecDidAwaken
{
return YES;
}
/**
* Internal flush operation ... writes data out from us, but
* doesn't try any further. Only called in main thread.
*/
- (void) _flush
{
NSString *str = nil;
if (inFlush == YES)
{
return;
}
[lock lock];
if (NO == inFlush && [message length] > 0)
{
inFlush = YES;
str = [message copy];
[message setString: @""];
}
[lock unlock];
if (nil != str)
{
BOOL ok = YES;
if (LT_DEBUG != type)
{
if (nil == serverName)
{
id<CmdLogger> server;
NS_DURING
{
server = (id<CmdLogger>)[EcProc cmdNewServer];
}
NS_HANDLER
{
server = nil;
NSLog(@"Exception contacting Command server: %@\n",
localException);
}
NS_ENDHANDLER
if (server != nil)
{
NS_DURING
{
[server logMessage: str
type: type
for: EcProc];
}
NS_HANDLER
{
NSLog(@"Exception sending info to logger: %@",
localException);
ok = NO;
}
NS_ENDHANDLER
}
else
{
ok = NO;
}
}
else
{
id<CmdLogger> server;
NS_DURING
{
server = (id<CmdLogger>)
[EcProc server: serverName];
}
NS_HANDLER
{
server = nil;
NSLog(@"Exception contacting logging server: %@\n",
localException);
}
NS_ENDHANDLER
if (server != nil)
{
NS_DURING
{
[server logMessage: str
type: type
for: self];
}
NS_HANDLER
{
NSLog(@"Exception sending info to %@: %@",
serverName, localException);
ok = NO;
}
NS_ENDHANDLER
}
else
{
ok = NO;
}
}
}
if (NO == ok)
{
if (nil == serverName)
{
NSLog(@"%@", str);
}
else
{
NSLog(@"Unable to log to %@ - %@", serverName, str);
}
DESTROY(str);
/*
* Flush any messages that might have been generated by
* (or during) our failed attempt to contact server.
*/
[lock lock];
if ([message length] > 0)
{
str = [message copy];
[message setString: @""];
}
[lock unlock];
if (nil != str)
{
NSLog(@"%@", str);
}
}
RELEASE(str);
[lock lock];
inFlush = NO;
[lock unlock];
}
}
/* ONLY called in main thread.
*/
- (void) _externalFlush: (id)dummy
{
if (externalFlush == NO)
{
externalFlush = YES;
[self _flush];
if (LT_DEBUG != type)
{
id<CmdLogger> server;
if (serverName == nil)
{
NS_DURING
{
server = (id<CmdLogger>)[EcProc cmdNewServer];
}
NS_HANDLER
{
server = nil;
NSLog(@"Exception contacting Command server: %@\n",
localException);
}
NS_ENDHANDLER
}
else
{
NS_DURING
{
server = (id<CmdLogger>)
[EcProc server: serverName];
}
NS_HANDLER
{
server = nil;
NSLog(@"Exception contacting logging server: %@\n",
localException);
}
NS_ENDHANDLER
}
if (server != nil)
{
NS_DURING
{
[server flush]; // Force round trip.
}
NS_HANDLER
{
NSLog(@"Exception flushing info to %@: %@",
serverName, localException);
}
NS_ENDHANDLER
}
}
externalFlush = NO;
}
}
/**
* External flush operation ... writes out data and asks any server
* we write to to flush its data out too.
*/
- (void) flush
{
[self performSelectorOnMainThread: @selector(_externalFlush:)
withObject: nil
waitUntilDone: YES
modes: modes];
}
/* This is ONLY called in the main thread.
*/
- (void) _scheduleFlush: (id)reset
{
/* A non-nil value of reset means that we should reset to do
* a flush real soon.
*/
[lock lock];
pendingFlush = NO;
if (reset != nil)
{
if (timer != nil && [[timer fireDate] timeIntervalSinceNow] > 0.001)
{
[timer invalidate];
timer = nil;
}
if (timer == nil)
{
timer = [NSTimer scheduledTimerWithTimeInterval: 0.0001
target: self selector: @selector(_timeout:)
userInfo: nil repeats: NO];
}
}
else if ([message length] >= size)
{
/*
* Buffer too large - schedule immediate flush.
*/
if (timer != nil && [[timer fireDate] timeIntervalSinceNow] > 0.001)
{
[timer invalidate];
timer = nil;
}
if (timer == nil)
{
timer = [NSTimer scheduledTimerWithTimeInterval: 0.0001
target: self selector: @selector(_timeout:)
userInfo: nil repeats: NO];
}
}
else if (interval > 0.0 && timer == nil)
{
/*
* No timer running - so schedule one to output the debug info.
*/
timer = [NSTimer scheduledTimerWithTimeInterval: interval
target: self selector: @selector(_timeout:)
userInfo: nil repeats: NO];
}
[lock unlock];
}
- (void) log: (NSString*)fmt arguments: (va_list)args
{
NSString *format;
format = [[NSString alloc] initWithFormat: @"%@ - %@", cmdLogKey(type), fmt];
NSLogv(format, args);
RELEASE(format);
if (YES == shouldForward)
{
CREATE_AUTORELEASE_POOL(arp);
NSString *text;
BOOL shouldFlush = NO;
format = cmdLogFormat(type, fmt);
text = [NSString stringWithFormat: format arguments: args];
[lock lock];
if (message == nil)
{
message = [[NSMutableString alloc] initWithCapacity: 1024];
}
[message appendString: text];
if ([message length] >= size || (interval > 0.0 && timer == nil))
{
if (NO == pendingFlush)
{
shouldFlush = YES;
pendingFlush = YES;
}
}
[lock unlock];
if (YES == shouldFlush)
{
[self performSelectorOnMainThread: @selector(_scheduleFlush:)
withObject: nil
waitUntilDone: NO
modes: modes];
}
RELEASE(arp);
}
}
- (void) log: (NSString*)fmt, ...
{
va_list ap;
va_start (ap, fmt);
[self log: fmt arguments: ap];
va_end (ap);
}
/* Should only be called on main thread.
*/
- (void) _timeout: (NSTimer*)t
{
if (t == nil)
{
[timer invalidate];
}
timer = nil;
[self _flush];
}
/* Should only execute on main thread.
*/
- (void) update
{
NSUserDefaults *defs;
NSString *str;
if (NO == [NSThread isMainThread])
{
[self performSelectorOnMainThread: @selector(update)
withObject: nil
waitUntilDone: NO
modes: modes];
return;
}
defs = [EcProc cmdDefaults];
/*
* If there is a server specified for this debug logger, we want it
* registered so we can use it - otherwise we will default to using
* the Command server for logging.
*/
str = [defs stringForKey: serverKey];
if ([str isEqual: @""] == YES)
{
str = nil; // An empty string means no server is used.
}
if ([serverName isEqual: str] == NO)
{
if (serverName != nil)
{
[EcProc removeServerFromList: serverName];
}
ASSIGN(serverName, str);
if (serverName != nil)
{
[EcProc addServerToList: serverName for: self];
}
}
/* Is the program to flush at intervals or at
* a particular buffer size (or both)?
*/
str = [defs stringForKey: flushKey];
if (str == nil)
{
str = [defs stringForKey: @"DefaultFlush"]; // Default settings.
}
if (str != nil)
{
NSScanner *scanner = [NSScanner scannerWithString: str];
float f;
int i;
if ([scanner scanFloat: &f] == YES)
{
interval = (floor(interval * 1000)) / 1000.0;
if (f < 0.0)
interval = 0.0;
else
interval = f;
}
if (([scanner scanString: @":" intoString: 0] == YES)
&& ([scanner scanInt: &i] == YES))
{
if (i < 0)
size = 0;
else
size = i*1024;
}
/*
* Ensure new values take effect real soon.
*/
if (NO == pendingFlush)
{
[self performSelectorOnMainThread: @selector(_scheduleFlush:)
withObject: self
waitUntilDone: NO
modes: modes];
}
}
}
@end