Oolite
Loading...
Searching...
No Matches
OOLogOutputHandler.m
Go to the documentation of this file.
1/*
2
3OOLogOutputHandler.m
4By Jens Ayton
5
6
7Copyright (C) 2007-2013 Jens Ayton and contributors
8
9Permission is hereby granted, free of charge, to any person obtaining a copy
10of this software and associated documentation files (the "Software"), to deal
11in the Software without restriction, including without limitation the rights
12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13copies of the Software, and to permit persons to whom the Software is
14furnished to do so, subject to the following conditions:
15
16The above copyright notice and this permission notice shall be included in all
17copies or substantial portions of the Software.
18
19THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25SOFTWARE.
26
27*/
28
29#define OOLOG_POISON_NSLOG 0
30
34#import "OOAsyncQueue.h"
35#import "OOLogging.h"
36#include <SDL3/SDL_stdinc.h>
37#include <stdio.h>
38#include <stdlib.h>
39
40#undef NSLog // We need to be able to call the real NSLog.
41
42#if OOLITE_MAC_OS_X
43
44#include <dlfcn.h>
45
46#ifndef NDEBUG
47
48#define SET_CRASH_REPORTER_INFO 1
49
50// Function to set "Application Specific Information" field in crash reporter log in Leopard.
51// Extremely unsupported, so not used in release builds.
52static void InitCrashReporterInfo(void);
53static void SetCrashReporterInfo(const char* info);
55
56#endif
57
58typedef void (*LogCStringFunctionProc)(const char* string, unsigned length, BOOL withSyslogBanner);
61
64
65static void LoadLogCStringFunctions(void);
66static void OONSLogCStringFunction(const char* string, unsigned length, BOOL withSyslogBanner);
67
68static NSString* GetAppName(void);
69
71
72#elif OOLITE_GNUSTEP
73
74static void OONSLogPrintfHandler(NSString* message);
75
76#else
77#error Unknown platform!
78#endif
79
80static BOOL DirectoryExistCreatingIfNecessary(NSString* path);
81
82#define kFlushInterval 2.0 // Lower bound on interval between explicit log file flushes.
83
84@interface OOAsyncLogger : NSObject {
85@private
87 NSConditionLock* threadStateMonitor;
88 NSFileHandle* logFile;
89 NSTimer* flushTimer;
90}
91
92- (void)asyncLogMessage:(NSString*)message;
93- (void)endLogging;
94
95- (void)changeFile;
96
97// Internal
98- (BOOL)startLogging;
99- (void)loggerThread;
100- (void)flushLog;
101
102@end
103
104static BOOL sInited = NO;
105static BOOL sWriteToStderr = YES;
106static BOOL sWriteToStdout = NO;
107static BOOL sSaturated = NO;
109static NSString* sLogFileName = @"Latest.log";
110
112{
113 if (sInited)
114 return;
115
116#if SET_CRASH_REPORTER_INFO
118#endif
119
120 sLogger = [[OOAsyncLogger alloc] init];
121 sInited = YES;
122
123 if (sLogger != nil) {
124 sWriteToStderr = [[NSUserDefaults standardUserDefaults] boolForKey:@"logging-echo-to-stderr"];
125 } else {
126 sWriteToStderr = YES;
127 }
128
129#if OOLITE_MAC_OS_X
131 if (_NSSetLogCStringFunction != NULL) {
134 } else {
135 OOLog(@"logging.nsLogFilter.install.failed", @"Failed to install NSLog() filter; system messages will not be logged in log file.");
136 }
137#elif GNUSTEP_BASE_LIBRARY
138 NSRecursiveLock* lock = GSLogLock();
139 [lock lock];
140 _NSLog_printf_handler = OONSLogPrintfHandler;
141 [lock unlock];
142#endif
143
145}
146
148{
149 if (sInited) {
150 sWriteToStderr = YES;
151 sInited = NO;
152
155
156#if OOLITE_MAC_OS_X
160 }
161#elif GNUSTEP_BASE_LIBRARY
162 NSRecursiveLock* lock = GSLogLock();
163 [lock lock];
164 _NSLog_printf_handler = NULL;
165 [lock unlock];
166#endif
167 }
168}
169
178
179void OOLogOutputHandlerPrint(NSString* string)
180{
181 if (sInited && sLogger != nil && !sWriteToStdout)
182 [sLogger asyncLogMessage:string];
183
184 BOOL doCStringStuff = sWriteToStderr || sWriteToStdout;
185#if SET_CRASH_REPORTER_INFO
186 doCStringStuff = doCStringStuff || sCrashReporterInfoAvailable;
187#endif
188
189 if (doCStringStuff) {
190 const char* cStr = [[string stringByAppendingString:@"\n"] UTF8String];
191 if (sWriteToStdout)
192 fputs(cStr, stdout);
193 else if (sWriteToStderr)
194 fputs(cStr, stderr);
195
196#if SET_CRASH_REPORTER_INFO
199#endif
200 }
201}
202
204{
205 return [OOLogHandlerGetLogBasePath() stringByAppendingPathComponent:sLogFileName];
206}
207
208void OOLogOutputHandlerChangeLogFile(NSString* newLogName)
209{
210 if (![sLogFileName isEqual:newLogName]) {
211 sLogFileName = [newLogName copy];
213 }
214}
215
216enum {
219};
220
221@implementation OOAsyncLogger
222
223- (id)init
224{
225 BOOL OK = YES;
226 NSString* logPath = nil;
227 NSString* oldPath = nil;
228 NSFileManager* fmgr = nil;
229
230 self = [super init];
231 if (self == nil)
232 OK = NO;
233
234 if (OK) {
235 fmgr = [NSFileManager defaultManager];
236 logPath = OOLogHandlerGetLogPath();
237
238 // If there is an existing file, move it to Previous.log.
239 if ([fmgr fileExistsAtPath:logPath]) {
240 oldPath = [OOLogHandlerGetLogBasePath() stringByAppendingPathComponent:@"Previous.log"];
241 [fmgr oo_removeItemAtPath:oldPath];
242 if (![fmgr oo_moveItemAtPath:logPath toPath:oldPath]) {
243 if (![fmgr oo_removeItemAtPath:logPath]) {
244 NSLog(@"Log setup: could not move or delete existing log at %@, will log to stdout instead.", logPath);
245 OK = NO;
246 }
247 }
248 }
249 }
250
251 if (OK)
252 OK = [self startLogging];
253
254 if (!OK)
255 DESTROY(self);
256
257 return self;
258}
259
260- (void)dealloc
261{
265 // We don't own a reference to flushTimer.
266
267 [super dealloc];
268}
269
271{
272 BOOL OK = YES;
273 NSString* logPath = nil;
274 NSFileManager* fmgr = nil;
275
276 fmgr = [NSFileManager defaultManager];
277
278 if (OK) {
279 messageQueue = [[OOAsyncQueue alloc] init];
280 if (messageQueue == nil)
281 OK = NO;
282 }
283
284 if (OK) {
285 // set up threadStateMonitor -- used as a binary semaphore of sorts to check when the worker thread starts and stops.
286 threadStateMonitor = [[NSConditionLock alloc] initWithCondition:kConditionReadyToDealloc];
287 if (threadStateMonitor == nil)
288 OK = NO;
289 [threadStateMonitor setName:@"OOLogOutputHandler.stateMonitor"];
290 }
291
292 if (OK) {
293 // Create work thread to actually handle messages.
294 // This needs to be done early to avoid messy state if something goes wrong.
295 [NSThread detachNewThreadSelector:@selector(loggerThread) toTarget:self withObject:nil];
296 // Wait for it to start.
297 if (![threadStateMonitor lockWhenCondition:kConditionWorking beforeDate:[NSDate dateWithTimeIntervalSinceNow:5.0]]) {
298 // If it doesn't signal a start within five seconds, assume something's wrong.
299 // Send kill signal, just in case it comes to life...
300 [messageQueue enqueue:@"die"];
301 // ...and stop -dealloc from waiting for thread death
302 [threadStateMonitor release];
304 OK = NO;
305 }
306 [threadStateMonitor unlockWithCondition:kConditionWorking];
307 }
308
309 if (OK) {
310 logPath = OOLogHandlerGetLogPath();
311 OK = (logPath != nil);
312 }
313
314 if (OK) {
315 // Create shiny new log file
316 OK = [fmgr createFileAtPath:logPath contents:nil attributes:nil];
317 if (OK) {
318 logFile = [[NSFileHandle fileHandleForWritingAtPath:logPath] retain];
319 OK = (logFile != nil);
320 }
321 if (!OK) {
322 NSLog(@"Log setup: could not open log at %@, will log to stdout instead.", logPath);
323 OK = NO;
324 }
325 }
326
327 return OK;
328}
329
331{
332 NSString* postamble = nil;
333
334 if (messageQueue != nil && threadStateMonitor != nil) {
335 // We're fully inited; write postamble, wait for worker thread to terminate cleanly, and close file.
336 postamble = [NSString stringWithFormat:@"\nClosing log at %@.", [NSDate date]];
337 [self asyncLogMessage:postamble];
338 [messageQueue enqueue:@"die"]; // Kill message
339 [threadStateMonitor lockWhenCondition:kConditionReadyToDealloc];
340 [threadStateMonitor unlock];
341
342 [logFile closeFile];
343 }
344}
345
347{
348 [self endLogging];
349 if (![self startLogging])
350 sWriteToStderr = YES;
351}
352
353- (void)asyncLogMessage:(NSString*)message
354{
355 // Don't log of saturated flag is set.
356 if (sSaturated)
357 return;
358
359 if (message != nil) {
360 message = [message stringByAppendingString:@"\n"];
361
362#if OOLITE_WINDOWS
363 // Convert Unix line endings to Windows ones.
364 NSArray* messageComponents = [message componentsSeparatedByString:@"\n"];
365 message = [messageComponents componentsJoinedByString:@"\r\n"];
366#endif
367
368 [messageQueue enqueue:[message dataUsingEncoding:NSUTF8StringEncoding]];
369
370 if (flushTimer == nil) {
371 // No pending flush
372 flushTimer = [NSTimer scheduledTimerWithTimeInterval:kFlushInterval target:self selector:@selector(flushLog) userInfo:nil repeats:NO];
373 }
374 }
375}
376
377- (void)flushLog
378{
379 flushTimer = nil;
380 [messageQueue enqueue:@"flush"];
381}
382
384{
385 id message = nil;
386 NSAutoreleasePool *rootPool = nil, *pool = nil;
387 NSUInteger size = 0;
388
389 rootPool = [[NSAutoreleasePool alloc] init];
390 [NSThread ooSetCurrentThreadName:@"loggerThread"];
391
392 // Signal readiness
393 [messageQueue retain];
394 [threadStateMonitor lock];
395 [threadStateMonitor unlockWithCondition:kConditionWorking];
396
397 @try {
398 for (;;) {
399 pool = [[NSAutoreleasePool alloc] init];
400
401 message = [messageQueue dequeue];
402
403 if (!sSaturated && [message isKindOfClass:[NSData class]]) {
404 size += [message length];
405 if (size > 1 << 30) // 1 GiB
406 {
407 sSaturated = YES;
408#if OOLITE_WINDOWS
409 message = @"\r\n\r\n\r\n***** LOG TRUNCATED DUE TO EXCESSIVE LENGTH *****\r\n";
410#else
411 message = @"\n\n\n***** LOG TRUNCATED DUE TO EXCESSIVE LENGTH *****\n";
412#endif
413 message = [message dataUsingEncoding:NSUTF8StringEncoding];
414 }
415
416 [logFile writeData:message];
417 } else if ([message isEqual:@"flush"]) {
418 [logFile synchronizeFile];
419 } else if ([message isEqual:@"die"]) {
420 break;
421 }
422
423 [pool release];
424 }
425 }
426 @catch (NSException* exception) {
427 }
428 [pool release];
429
430 // Clean up; after this, ivars are out of bounds.
431 [messageQueue release];
432 [threadStateMonitor lock];
433 [threadStateMonitor unlockWithCondition:kConditionReadyToDealloc];
434
435 [rootPool release];
436}
437
438@end
439
440#if OOLITE_MAC_OS_X
441
442/* LoadLogCStringFunctions()
443
444 We wish to make NSLogv() call our custom function OONSLogCStringFunction()
445 rather than printing to stdout, by calling _NSSetLogCStringFunction().
446 Additionally, in order to close the logger cleanly, we wish to be able to
447 restore the standard logger, which requires us to call
448 _NSLogCStringFunction(). These functions are private.
449 _NSLogCStringFunction() is undocumented. _NSSetLogCStringFunction() is
450 documented at http://docs.info.apple.com/article.html?artnum=70081 ,
451 with the warning:
452
453 Be aware that this code references private APIs; this is an
454 unsupported workaround and users should use these instructions at
455 their own risk. Apple will not guarantee or provide support for
456 this procedure.
457
458 The approach taken here is to load the functions dynamically. This makes
459 us safe in the case of Apple removing the functions. In the unlikely event
460 that they change the functions' paramters without renaming them, we would
461 have a problem.
462*/
463static void LoadLogCStringFunctions(void)
464{
465 CFBundleRef foundationBundle = NULL;
466 LogCStringFunctionGetterProc getter = NULL;
467 LogCStringFunctionSetterProc setter = NULL;
468
469 foundationBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Foundation"));
470 if (foundationBundle != NULL) {
471 getter = CFBundleGetFunctionPointerForName(foundationBundle, CFSTR("_NSLogCStringFunction"));
472 setter = CFBundleGetFunctionPointerForName(foundationBundle, CFSTR("_NSSetLogCStringFunction"));
473
474 if (getter != NULL && setter != NULL) {
475 _NSLogCStringFunction = getter;
477 }
478 }
479}
480
481static void OONSLogCStringFunction(const char* string, unsigned length, BOOL withSyslogBanner)
482{
483 if (OOLogWillDisplayMessagesInClass(@"system")) {
484 OOLogWithFunctionFileAndLine(@"system", NULL, NULL, 0, @"%s", string);
485 }
486}
487
488#elif OOLITE_GNUSTEP
489
490static void OONSLogPrintfHandler(NSString* message)
491{
492 if (OOLogWillDisplayMessagesInClass(@"gnustep")) {
493 OOLogWithFunctionFileAndLine(@"gnustep", NULL, NULL, 0, @"%@", message);
494 }
495}
496
497#endif
498
499static BOOL DirectoryExistCreatingIfNecessary(NSString* path)
500{
501 BOOL exists, directory;
502 NSFileManager* fmgr = [NSFileManager defaultManager];
503
504 exists = [fmgr fileExistsAtPath:path isDirectory:&directory];
505
506 if (exists && !directory) {
507 NSLog(@"Log setup: expected %@ to be a folder, but it is a file.", path);
508 return NO;
509 }
510 if (!exists) {
511 if (![fmgr oo_createDirectoryAtPath:path attributes:nil]) {
512 NSLog(@"Log setup: could not create folder %@.", path);
513 return NO;
514 }
515 }
516
517 return YES;
518}
519
520#if OOLITE_MAC_OS_X
521static void ExcludeFromTimeMachine(NSString* path)
522{
523 OSStatus (*CSBackupSetItemExcluded)(NSURL* item, Boolean exclude, Boolean excludeByPath) = NULL;
524 CFBundleRef carbonCoreBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CoreServices.CarbonCore"));
525 if (carbonCoreBundle) {
526 CSBackupSetItemExcluded = CFBundleGetFunctionPointerForName(carbonCoreBundle, CFSTR("CSBackupSetItemExcluded"));
527 if (CSBackupSetItemExcluded != NULL) {
528 (void)CSBackupSetItemExcluded([NSURL fileURLWithPath:path], YES, NO);
529 }
530 }
531}
532
533static NSString* GetAppName(void)
534{
535 static NSString* appName = nil;
536 NSBundle* bundle = nil;
537
538 if (appName == nil) {
539 bundle = [NSBundle mainBundle];
540 appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
541 if (appName == nil)
542 appName = [bundle bundleIdentifier];
543 if (appName == nil)
544 appName = @"<unknown application>";
545 [appName retain];
546 }
547
548 return appName;
549}
550#endif
551
553{
554 static NSString* basePath = nil;
555
556 if (basePath == nil) {
557 const char* logdirEnv = SDL_getenv("OO_LOGSDIR");
558
559 if (logdirEnv) {
560 basePath = [NSString stringWithUTF8String:logdirEnv];
561 } else {
562#if OOLITE_MAC_OS_X
563 // ~/Library
564 basePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
565#elif OOLITE_LINUX
566 // ~
567 basePath = NSHomeDirectory();
568
569 // ~/.Oolite
570 basePath = [basePath stringByAppendingPathComponent:@".Oolite"];
572 return nil;
573#elif OOLITE_WINDOWS
574 // <Install path>\Oolite
575 basePath = NSHomeDirectory();
576#endif
577
578 // .../Logs
579 basePath = [basePath stringByAppendingPathComponent:@"Logs"];
581 return nil;
582
583#if OOLITE_MAC_OS_X
584 // ~/Library/Logs/Oolite
585 basePath = [basePath stringByAppendingPathComponent:GetAppName()];
587 return nil;
588#endif
589 }
590#if OOLITE_MAC_OS_X
591 ExcludeFromTimeMachine(basePath);
592#endif
593 [basePath retain];
594 }
595
596 return basePath;
597}
598
599#if SET_CRASH_REPORTER_INFO
600
601static char** sCrashReporterInfo = NULL;
602static char* sOldCrashReporterInfo = NULL;
604
605// Evil hackery based on http://www.allocinit.net/blog/2008/01/04/application-specific-information-in-leopard-crash-reports/
606static void InitCrashReporterInfo(void)
607{
608 sCrashReporterInfo = dlsym(RTLD_DEFAULT, "__crashreporter_info__");
609 if (sCrashReporterInfo != NULL) {
610 sCrashReporterInfoLock = [[NSLock alloc] init];
613 } else {
614 sCrashReporterInfo = NULL;
615 }
616 }
617}
618
619static void SetCrashReporterInfo(const char* info)
620{
621 char *copy = NULL, *old = NULL;
622
623 /* Don't do anything if setup failed or the string is NULL or empty.
624 (The NULL and empty checks may not be desirable in other uses.)
625 */
626 if (!sCrashReporterInfoAvailable || info == NULL || *info == '\0')
627 return;
628
629 // Copy the string, which we assume to be dynamic...
630 copy = strdup(info);
631 if (copy == NULL)
632 return;
633
634 /* ...and swap it in.
635 Note that we keep a separate pointer to the old value, in case
636 something else overwrites __crashreporter_info__.
637 */
638 [sCrashReporterInfoLock lock];
639 *sCrashReporterInfo = copy;
642 [sCrashReporterInfoLock unlock];
643
644 // Delete our old string.
645 if (old != NULL)
646 free(old);
647}
648
649#endif
static BOOL sInited
Definition OOCPUInfo.m:56
#define DESTROY(x)
void OOLogOutputHandlerClose(void)
static void SetCrashReporterInfo(const char *info)
static LogCStringFunctionSetterProc _NSSetLogCStringFunction
@ kConditionReadyToDealloc
@ kConditionWorking
void OOLogOutputHandlerPrint(NSString *string)
static NSString * sLogFileName
static NSString * GetAppName(void)
static char * sOldCrashReporterInfo
void OOLogOutputHandlerStartLoggingToStdout()
NSString * OOLogHandlerGetLogPath(void)
void OOLogOutputHandlerClose(void)
static NSLock * sCrashReporterInfoLock
void OOLogOutputHandlerChangeLogFile(NSString *newLogName)
static LogCStringFunctionGetterProc _NSLogCStringFunction
static LogCStringFunctionProc sDefaultLogCStringFunction
static OOAsyncLogger * sLogger
LogCStringFunctionProc(* LogCStringFunctionGetterProc)(void)
NSString * OOLogHandlerGetLogBasePath(void)
static char ** sCrashReporterInfo
void OOLogOutputHandlerInit(void)
static BOOL sCrashReporterInfoAvailable
static void InitCrashReporterInfo(void)
static BOOL sSaturated
static BOOL sWriteToStderr
void(* LogCStringFunctionSetterProc)(LogCStringFunctionProc)
static void LoadLogCStringFunctions(void)
static BOOL DirectoryExistCreatingIfNecessary(NSString *path)
static BOOL sWriteToStdout
static void ExcludeFromTimeMachine(NSString *path)
void(* LogCStringFunctionProc)(const char *string, unsigned length, BOOL withSyslogBanner)
void OOLogOutputHandlerStopLoggingToStdout()
static void OONSLogCStringFunction(const char *string, unsigned length, BOOL withSyslogBanner)
#define NSLog(format,...)
Definition OOLogging.h:148
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
#define OOLog(class, format,...)
Definition OOLogging.h:84
void void OOLogWithFunctionFileAndLine(NSString *inMessageClass, const char *inFunction, const char *inFile, unsigned long inLine, NSString *inFormat,...) OO_TAKES_FORMAT_STRING(5
return nil
OOAsyncQueue * messageQueue
NSFileHandle * logFile
void asyncLogMessage:(NSString *message)
NSConditionLock * threadStateMonitor
BOOL enqueue:(id object)
voidpf void uLong size
Definition ioapi.h:126