Proyectos de Subversion Iphone Microlearning

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// Copyright 2018 Google
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
 
15
#import "GoogleUtilities/Logger/Public/GoogleUtilities/GULLogger.h"
16
 
17
#include <asl.h>
18
 
19
#import "GoogleUtilities/Environment/Public/GoogleUtilities/GULAppEnvironmentUtil.h"
20
#import "GoogleUtilities/Logger/Public/GoogleUtilities/GULLoggerLevel.h"
21
 
22
/// ASL client facility name used by GULLogger.
23
const char *kGULLoggerASLClientFacilityName = "com.google.utilities.logger";
24
 
25
static dispatch_once_t sGULLoggerOnceToken;
26
 
27
static aslclient sGULLoggerClient;
28
 
29
static dispatch_queue_t sGULClientQueue;
30
 
31
static BOOL sGULLoggerDebugMode;
32
 
33
static GULLoggerLevel sGULLoggerMaximumLevel;
34
 
35
// Allow clients to register a version to include in the log.
36
static NSString *sVersion = @"";
37
 
38
static GULLoggerService kGULLoggerLogger = @"[GULLogger]";
39
 
40
#ifdef DEBUG
41
/// The regex pattern for the message code.
42
static NSString *const kMessageCodePattern = @"^I-[A-Z]{3}[0-9]{6}$";
43
static NSRegularExpression *sMessageCodeRegex;
44
#endif
45
 
46
void GULLoggerInitializeASL(void) {
47
  dispatch_once(&sGULLoggerOnceToken, ^{
48
    NSInteger majorOSVersion = [[GULAppEnvironmentUtil systemVersion] integerValue];
49
    uint32_t aslOptions = ASL_OPT_STDERR;
50
#if TARGET_OS_SIMULATOR
51
    // The iOS 11 simulator doesn't need the ASL_OPT_STDERR flag.
52
    if (majorOSVersion >= 11) {
53
      aslOptions = 0;
54
    }
55
#else
56
    // Devices running iOS 10 or higher don't need the ASL_OPT_STDERR flag.
57
    if (majorOSVersion >= 10) {
58
      aslOptions = 0;
59
    }
60
#endif  // TARGET_OS_SIMULATOR
61
 
62
#pragma clang diagnostic push
63
#pragma clang diagnostic ignored "-Wdeprecated-declarations"  // asl is deprecated
64
    // Initialize the ASL client handle.
65
    sGULLoggerClient = asl_open(NULL, kGULLoggerASLClientFacilityName, aslOptions);
66
    sGULLoggerMaximumLevel = GULLoggerLevelNotice;
67
 
68
    // Set the filter used by system/device log. Initialize in default mode.
69
    asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_NOTICE));
70
 
71
    sGULClientQueue = dispatch_queue_create("GULLoggingClientQueue", DISPATCH_QUEUE_SERIAL);
72
    dispatch_set_target_queue(sGULClientQueue,
73
                              dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
74
#ifdef DEBUG
75
    sMessageCodeRegex = [NSRegularExpression regularExpressionWithPattern:kMessageCodePattern
76
                                                                  options:0
77
                                                                    error:NULL];
78
#endif
79
  });
80
}
81
 
82
void GULLoggerEnableSTDERR(void) {
83
  asl_add_log_file(sGULLoggerClient, STDERR_FILENO);
84
}
85
 
86
void GULLoggerForceDebug(void) {
87
  // We should enable debug mode if we're not running from App Store.
88
  if (![GULAppEnvironmentUtil isFromAppStore]) {
89
    sGULLoggerDebugMode = YES;
90
    GULSetLoggerLevel(GULLoggerLevelDebug);
91
  }
92
}
93
 
94
__attribute__((no_sanitize("thread"))) void GULSetLoggerLevel(GULLoggerLevel loggerLevel) {
95
  if (loggerLevel < GULLoggerLevelMin || loggerLevel > GULLoggerLevelMax) {
96
    GULLogError(kGULLoggerLogger, NO, @"I-COR000023", @"Invalid logger level, %ld",
97
                (long)loggerLevel);
98
    return;
99
  }
100
  GULLoggerInitializeASL();
101
  // We should not raise the logger level if we are running from App Store.
102
  if (loggerLevel >= GULLoggerLevelNotice && [GULAppEnvironmentUtil isFromAppStore]) {
103
    return;
104
  }
105
 
106
  sGULLoggerMaximumLevel = loggerLevel;
107
  dispatch_async(sGULClientQueue, ^{
108
    asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(loggerLevel));
109
  });
110
}
111
 
112
/**
113
 * Check if the level is high enough to be loggable.
114
 */
115
__attribute__((no_sanitize("thread"))) BOOL GULIsLoggableLevel(GULLoggerLevel loggerLevel) {
116
  GULLoggerInitializeASL();
117
  if (sGULLoggerDebugMode) {
118
    return YES;
119
  }
120
  return (BOOL)(loggerLevel <= sGULLoggerMaximumLevel);
121
}
122
 
123
#ifdef DEBUG
124
void GULResetLogger(void) {
125
  sGULLoggerOnceToken = 0;
126
  sGULLoggerDebugMode = NO;
127
}
128
 
129
aslclient getGULLoggerClient(void) {
130
  return sGULLoggerClient;
131
}
132
 
133
dispatch_queue_t getGULClientQueue(void) {
134
  return sGULClientQueue;
135
}
136
 
137
BOOL getGULLoggerDebugMode(void) {
138
  return sGULLoggerDebugMode;
139
}
140
#endif
141
 
142
void GULLoggerRegisterVersion(NSString *version) {
143
  sVersion = version;
144
}
145
 
146
void GULLogBasic(GULLoggerLevel level,
147
                 GULLoggerService service,
148
                 BOOL forceLog,
149
                 NSString *messageCode,
150
                 NSString *message,
151
                 va_list args_ptr) {
152
  GULLoggerInitializeASL();
153
  if (!(level <= sGULLoggerMaximumLevel || sGULLoggerDebugMode || forceLog)) {
154
    return;
155
  }
156
 
157
#ifdef DEBUG
158
  NSCAssert(messageCode.length == 11, @"Incorrect message code length.");
159
  NSRange messageCodeRange = NSMakeRange(0, messageCode.length);
160
  NSUInteger numberOfMatches = [sMessageCodeRegex numberOfMatchesInString:messageCode
161
                                                                  options:0
162
                                                                    range:messageCodeRange];
163
  NSCAssert(numberOfMatches == 1, @"Incorrect message code format.");
164
#endif
165
  NSString *logMsg;
166
  if (args_ptr == NULL) {
167
    logMsg = message;
168
  } else {
169
    logMsg = [[NSString alloc] initWithFormat:message arguments:args_ptr];
170
  }
171
  logMsg = [NSString stringWithFormat:@"%@ - %@[%@] %@", sVersion, service, messageCode, logMsg];
172
  dispatch_async(sGULClientQueue, ^{
173
    asl_log(sGULLoggerClient, NULL, (int)level, "%s", logMsg.UTF8String);
174
  });
175
}
176
#pragma clang diagnostic pop
177
 
178
/**
179
 * Generates the logging functions using macros.
180
 *
181
 * Calling GULLogError({service}, @"I-XYZ000001", @"Configure %@ failed.", @"blah") shows:
182
 * yyyy-mm-dd hh:mm:ss.SSS sender[PID] <Error> [{service}][I-XYZ000001] Configure blah failed.
183
 * Calling GULLogDebug({service}, @"I-XYZ000001", @"Configure succeed.") shows:
184
 * yyyy-mm-dd hh:mm:ss.SSS sender[PID] <Debug> [{service}][I-XYZ000001] Configure succeed.
185
 */
186
#define GUL_LOGGING_FUNCTION(level)                                                     \
187
  void GULLog##level(GULLoggerService service, BOOL force, NSString *messageCode,       \
188
                     NSString *message, ...) {                                          \
189
    va_list args_ptr;                                                                   \
190
    va_start(args_ptr, message);                                                        \
191
    GULLogBasic(GULLoggerLevel##level, service, force, messageCode, message, args_ptr); \
192
    va_end(args_ptr);                                                                   \
193
  }
194
 
195
GUL_LOGGING_FUNCTION(Error)
196
GUL_LOGGING_FUNCTION(Warning)
197
GUL_LOGGING_FUNCTION(Notice)
198
GUL_LOGGING_FUNCTION(Info)
199
GUL_LOGGING_FUNCTION(Debug)
200
 
201
#undef GUL_MAKE_LOGGER
202
 
203
#pragma mark - GULLoggerWrapper
204
 
205
@implementation GULLoggerWrapper
206
 
207
+ (void)logWithLevel:(GULLoggerLevel)level
208
         withService:(GULLoggerService)service
209
            withCode:(NSString *)messageCode
210
         withMessage:(NSString *)message
211
            withArgs:(va_list)args {
212
  GULLogBasic(level, service, NO, messageCode, message, args);
213
}
214
 
215
@end