No Description

GULLogger.m 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. #import "Private/GULLogger.h"
  15. #include <asl.h>
  16. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  17. #import <GoogleUtilities/GULLoggerLevel.h>
  18. /// ASL client facility name used by GULLogger.
  19. const char *kGULLoggerASLClientFacilityName = "com.google.utilities.logger";
  20. static dispatch_once_t sGULLoggerOnceToken;
  21. static aslclient sGULLoggerClient;
  22. static dispatch_queue_t sGULClientQueue;
  23. static BOOL sGULLoggerDebugMode;
  24. static GULLoggerLevel sGULLoggerMaximumLevel;
  25. // Allow clients to register a version to include in the log.
  26. static const char *sVersion = "";
  27. static GULLoggerService kGULLoggerLogger = @"[GULLogger]";
  28. #ifdef DEBUG
  29. /// The regex pattern for the message code.
  30. static NSString *const kMessageCodePattern = @"^I-[A-Z]{3}[0-9]{6}$";
  31. static NSRegularExpression *sMessageCodeRegex;
  32. #endif
  33. void GULLoggerInitializeASL(void) {
  34. dispatch_once(&sGULLoggerOnceToken, ^{
  35. NSInteger majorOSVersion = [[GULAppEnvironmentUtil systemVersion] integerValue];
  36. uint32_t aslOptions = ASL_OPT_STDERR;
  37. #if TARGET_OS_SIMULATOR
  38. // The iOS 11 simulator doesn't need the ASL_OPT_STDERR flag.
  39. if (majorOSVersion >= 11) {
  40. aslOptions = 0;
  41. }
  42. #else
  43. // Devices running iOS 10 or higher don't need the ASL_OPT_STDERR flag.
  44. if (majorOSVersion >= 10) {
  45. aslOptions = 0;
  46. }
  47. #endif // TARGET_OS_SIMULATOR
  48. #pragma clang diagnostic push
  49. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // asl is deprecated
  50. // Initialize the ASL client handle.
  51. sGULLoggerClient = asl_open(NULL, kGULLoggerASLClientFacilityName, aslOptions);
  52. sGULLoggerMaximumLevel = GULLoggerLevelNotice;
  53. // Set the filter used by system/device log. Initialize in default mode.
  54. asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_NOTICE));
  55. sGULClientQueue = dispatch_queue_create("GULLoggingClientQueue", DISPATCH_QUEUE_SERIAL);
  56. dispatch_set_target_queue(sGULClientQueue,
  57. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
  58. #ifdef DEBUG
  59. sMessageCodeRegex = [NSRegularExpression regularExpressionWithPattern:kMessageCodePattern
  60. options:0
  61. error:NULL];
  62. #endif
  63. });
  64. }
  65. void GULLoggerEnableSTDERR(void) {
  66. asl_add_log_file(sGULLoggerClient, STDERR_FILENO);
  67. }
  68. void GULLoggerForceDebug(void) {
  69. // We should enable debug mode if we're not running from App Store.
  70. if (![GULAppEnvironmentUtil isFromAppStore]) {
  71. sGULLoggerDebugMode = YES;
  72. GULSetLoggerLevel(GULLoggerLevelDebug);
  73. }
  74. }
  75. __attribute__((no_sanitize("thread"))) void GULSetLoggerLevel(GULLoggerLevel loggerLevel) {
  76. if (loggerLevel < GULLoggerLevelMin || loggerLevel > GULLoggerLevelMax) {
  77. GULLogError(kGULLoggerLogger, NO, @"I-COR000023", @"Invalid logger level, %ld",
  78. (long)loggerLevel);
  79. return;
  80. }
  81. GULLoggerInitializeASL();
  82. // We should not raise the logger level if we are running from App Store.
  83. if (loggerLevel >= GULLoggerLevelNotice && [GULAppEnvironmentUtil isFromAppStore]) {
  84. return;
  85. }
  86. sGULLoggerMaximumLevel = loggerLevel;
  87. dispatch_async(sGULClientQueue, ^{
  88. asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(loggerLevel));
  89. });
  90. }
  91. /**
  92. * Check if the level is high enough to be loggable.
  93. */
  94. __attribute__((no_sanitize("thread"))) BOOL GULIsLoggableLevel(GULLoggerLevel loggerLevel) {
  95. GULLoggerInitializeASL();
  96. if (sGULLoggerDebugMode) {
  97. return YES;
  98. }
  99. return (BOOL)(loggerLevel <= sGULLoggerMaximumLevel);
  100. }
  101. #ifdef DEBUG
  102. void GULResetLogger() {
  103. sGULLoggerOnceToken = 0;
  104. }
  105. aslclient getGULLoggerClient() {
  106. return sGULLoggerClient;
  107. }
  108. dispatch_queue_t getGULClientQueue() {
  109. return sGULClientQueue;
  110. }
  111. BOOL getGULLoggerDebugMode() {
  112. return sGULLoggerDebugMode;
  113. }
  114. #endif
  115. void GULLoggerRegisterVersion(const char *version) {
  116. sVersion = version;
  117. }
  118. void GULLogBasic(GULLoggerLevel level,
  119. GULLoggerService service,
  120. BOOL forceLog,
  121. NSString *messageCode,
  122. NSString *message,
  123. va_list args_ptr) {
  124. GULLoggerInitializeASL();
  125. if (!(level <= sGULLoggerMaximumLevel || sGULLoggerDebugMode || forceLog)) {
  126. return;
  127. }
  128. #ifdef DEBUG
  129. NSCAssert(messageCode.length == 11, @"Incorrect message code length.");
  130. NSRange messageCodeRange = NSMakeRange(0, messageCode.length);
  131. NSUInteger numberOfMatches = [sMessageCodeRegex numberOfMatchesInString:messageCode
  132. options:0
  133. range:messageCodeRange];
  134. NSCAssert(numberOfMatches == 1, @"Incorrect message code format.");
  135. #endif
  136. NSString *logMsg;
  137. if (args_ptr == NULL) {
  138. logMsg = message;
  139. } else {
  140. logMsg = [[NSString alloc] initWithFormat:message arguments:args_ptr];
  141. }
  142. logMsg = [NSString stringWithFormat:@"%s - %@[%@] %@", sVersion, service, messageCode, logMsg];
  143. dispatch_async(sGULClientQueue, ^{
  144. asl_log(sGULLoggerClient, NULL, (int)level, "%s", logMsg.UTF8String);
  145. });
  146. }
  147. #pragma clang diagnostic pop
  148. /**
  149. * Generates the logging functions using macros.
  150. *
  151. * Calling GULLogError(kGULLoggerCore, @"I-COR000001", @"Configure %@ failed.", @"blah") shows:
  152. * yyyy-mm-dd hh:mm:ss.SSS sender[PID] <Error> [{service}][I-COR000001] Configure blah failed.
  153. * Calling GULLogDebug(kGULLoggerCore, @"I-COR000001", @"Configure succeed.") shows:
  154. * yyyy-mm-dd hh:mm:ss.SSS sender[PID] <Debug> [{service}][I-COR000001] Configure succeed.
  155. */
  156. #define GUL_LOGGING_FUNCTION(level) \
  157. void GULLog##level(GULLoggerService service, BOOL force, NSString *messageCode, \
  158. NSString *message, ...) { \
  159. va_list args_ptr; \
  160. va_start(args_ptr, message); \
  161. GULLogBasic(GULLoggerLevel##level, service, force, messageCode, message, args_ptr); \
  162. va_end(args_ptr); \
  163. }
  164. GUL_LOGGING_FUNCTION(Error)
  165. GUL_LOGGING_FUNCTION(Warning)
  166. GUL_LOGGING_FUNCTION(Notice)
  167. GUL_LOGGING_FUNCTION(Info)
  168. GUL_LOGGING_FUNCTION(Debug)
  169. #undef GUL_MAKE_LOGGER
  170. #pragma mark - GULLoggerWrapper
  171. @implementation GULLoggerWrapper
  172. + (void)logWithLevel:(GULLoggerLevel)level
  173. withService:(GULLoggerService)service
  174. withCode:(NSString *)messageCode
  175. withMessage:(NSString *)message
  176. withArgs:(va_list)args {
  177. GULLogBasic(level, service, NO, messageCode, message, args);
  178. }
  179. @end