Miscellaneous improvements.
5 // Created by Jens Alfke on 1/5/08.
6 // Copyright 2008 Jens Alfke. All rights reserved.
12 #include <sys/param.h>
15 NSString* LOC( NSString *key ) // Localized string lookup
17 NSString *value = [[NSBundle mainBundle] localizedStringForKey:key value:nil table:nil];
19 Warn(@"No localized string for '%@' in Localizable.strings!",key);
20 value = [key uppercaseString];
28 static NSMutableSet *sEnabledDomains;
31 static BOOL isConsole( int fd )
35 char path[MAXPATHLEN];
36 if( fcntl(fd, F_GETPATH, path) == -1 )
42 static void InitLogging()
44 if( _gShouldLog != -1 )
47 NSAutoreleasePool *pool = [NSAutoreleasePool new];
49 sEnabledDomains = [[NSMutableSet alloc] init];
50 NSDictionary *dflts = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
51 for( NSString *key in dflts ) {
52 if( [key hasPrefix: @"Log"] ) {
53 BOOL value = [[NSUserDefaults standardUserDefaults] boolForKey: key];
57 [sEnabledDomains addObject: [key substringFromIndex: 3]];
60 sConsole = isConsole(STDERR_FILENO);
62 Log(@"Logging enabled in domains: {%@}",
63 [[[sEnabledDomains allObjects] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)]
64 componentsJoinedByString: @", "]);
69 BOOL EnableLog( BOOL enable )
71 if( _gShouldLog == -1 )
73 BOOL old = _gShouldLog;
78 BOOL _WillLogTo( NSString *domain )
80 if( _gShouldLog == -1 )
82 return _gShouldLog && [sEnabledDomains containsObject: domain];
85 BOOL _EnableLogTo( NSString *domain, BOOL enable )
87 if( _gShouldLog == -1 )
89 BOOL old = [sEnabledDomains containsObject: domain];
91 [sEnabledDomains addObject: domain];
93 [sEnabledDomains removeObject: domain];
98 static void _Logv( NSString *prefix, NSString *msg, va_list args )
101 NSAutoreleasePool *pool = [NSAutoreleasePool new];
102 static NSDateFormatter *sTimestampFormat;
103 if( ! sTimestampFormat ) {
104 sTimestampFormat = [[NSDateFormatter alloc] init];
105 sTimestampFormat.dateFormat = @"HH:mm:ss.SSS";
107 NSDate *now = [[NSDate alloc] init];
108 NSString *timestamp = [sTimestampFormat stringFromDate: now];
110 NSString *separator = prefix.length ?@": " :@"";
111 msg = [[NSString alloc] initWithFormat: msg arguments: args];
112 NSString *finalMsg = [[NSString alloc] initWithFormat: @"%@| %@%@%@\n",
113 timestamp,prefix,separator,msg];
114 fputs([finalMsg UTF8String], stderr);
123 void AlwaysLog( NSString *msg, ... )
132 void _Log( NSString *msg, ... )
134 if( _gShouldLog == -1 )
145 void _LogTo( NSString *domain, NSString *msg, ... )
147 if( _gShouldLog == -1 )
149 if( _gShouldLog && [sEnabledDomains containsObject: domain] ) {
152 _Logv(domain, msg, args);
158 void Warn( NSString *msg, ... )
162 _Logv(@"WARNING*** ",msg,args);