You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

231 lines
8.2 KiB

  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2015, Deusty, LLC
  4. // All rights reserved.
  5. //
  6. // Redistribution and use of this software in source and binary forms,
  7. // with or without modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright notice,
  10. // this list of conditions and the following disclaimer.
  11. //
  12. // * Neither the name of Deusty nor the names of its contributors may be used
  13. // to endorse or promote products derived from this software without specific
  14. // prior written permission of Deusty, LLC.
  15. #import "DDASLLogCapture.h"
  16. // Disable legacy macros
  17. #ifndef DD_LEGACY_MACROS
  18. #define DD_LEGACY_MACROS 0
  19. #endif
  20. #import "DDLog.h"
  21. #include <asl.h>
  22. #include <notify.h>
  23. #include <notify_keys.h>
  24. #include <sys/time.h>
  25. static BOOL _cancel = YES;
  26. static DDLogLevel _captureLevel = DDLogLevelVerbose;
  27. #ifdef __IPHONE_8_0
  28. #define DDASL_IOS_PIVOT_VERSION __IPHONE_8_0
  29. #endif
  30. #ifdef __MAC_10_10
  31. #define DDASL_OSX_PIVOT_VERSION __MAC_10_10
  32. #endif
  33. @implementation DDASLLogCapture
  34. static aslmsg (*dd_asl_next)(aslresponse obj);
  35. static void (*dd_asl_release)(aslresponse obj);
  36. + (void)initialize
  37. {
  38. #if (defined(DDASL_IOS_PIVOT_VERSION) && __IPHONE_OS_VERSION_MAX_ALLOWED >= DDASL_IOS_PIVOT_VERSION) || (defined(DDASL_OSX_PIVOT_VERSION) && __MAC_OS_X_VERSION_MAX_ALLOWED >= DDASL_OSX_PIVOT_VERSION)
  39. #if __IPHONE_OS_VERSION_MIN_REQUIRED < DDASL_IOS_PIVOT_VERSION || __MAC_OS_X_VERSION_MIN_REQUIRED < DDASL_OSX_PIVOT_VERSION
  40. #pragma GCC diagnostic push
  41. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  42. // Building on falsely advertised SDK, targeting deprecated API
  43. dd_asl_next = &aslresponse_next;
  44. dd_asl_release = &aslresponse_free;
  45. #pragma GCC diagnostic pop
  46. #else
  47. // Building on lastest, correct SDK, targeting latest API
  48. dd_asl_next = &asl_next;
  49. dd_asl_release = &asl_release;
  50. #endif
  51. #else
  52. // Building on old SDKs, targeting deprecated API
  53. dd_asl_next = &aslresponse_next;
  54. dd_asl_release = &aslresponse_free;
  55. #endif
  56. }
  57. + (void)start {
  58. // Ignore subsequent calls
  59. if (!_cancel) {
  60. return;
  61. }
  62. _cancel = NO;
  63. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  64. [self captureAslLogs];
  65. });
  66. }
  67. + (void)stop {
  68. _cancel = YES;
  69. }
  70. + (DDLogLevel)captureLevel {
  71. return _captureLevel;
  72. }
  73. + (void)setCaptureLevel:(DDLogLevel)level {
  74. _captureLevel = level;
  75. }
  76. #pragma mark - Private methods
  77. + (void)configureAslQuery:(aslmsg)query {
  78. const char param[] = "7"; // ASL_LEVEL_DEBUG, which is everything. We'll rely on regular DDlog log level to filter
  79. asl_set_query(query, ASL_KEY_LEVEL, param, ASL_QUERY_OP_LESS_EQUAL | ASL_QUERY_OP_NUMERIC);
  80. // Don't retrieve logs from our own DDASLLogger
  81. asl_set_query(query, kDDASLKeyDDLog, kDDASLDDLogValue, ASL_QUERY_OP_NOT_EQUAL);
  82. #if !TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  83. int processId = [[NSProcessInfo processInfo] processIdentifier];
  84. char pid[16];
  85. sprintf(pid, "%d", processId);
  86. asl_set_query(query, ASL_KEY_PID, pid, ASL_QUERY_OP_EQUAL | ASL_QUERY_OP_NUMERIC);
  87. #endif
  88. }
  89. + (void)aslMessageReceived:(aslmsg)msg {
  90. const char* messageCString = asl_get( msg, ASL_KEY_MSG );
  91. if ( messageCString == NULL )
  92. return;
  93. int flag;
  94. BOOL async;
  95. const char* levelCString = asl_get(msg, ASL_KEY_LEVEL);
  96. switch (levelCString? atoi(levelCString) : 0) {
  97. // By default all NSLog's with a ASL_LEVEL_WARNING level
  98. case ASL_LEVEL_EMERG :
  99. case ASL_LEVEL_ALERT :
  100. case ASL_LEVEL_CRIT : flag = DDLogFlagError; async = NO; break;
  101. case ASL_LEVEL_ERR : flag = DDLogFlagWarning; async = YES; break;
  102. case ASL_LEVEL_WARNING : flag = DDLogFlagInfo; async = YES; break;
  103. case ASL_LEVEL_NOTICE : flag = DDLogFlagDebug; async = YES; break;
  104. case ASL_LEVEL_INFO :
  105. case ASL_LEVEL_DEBUG :
  106. default : flag = DDLogFlagVerbose; async = YES; break;
  107. }
  108. if (!(_captureLevel & flag)) {
  109. return;
  110. }
  111. // NSString * sender = [NSString stringWithCString:asl_get(msg, ASL_KEY_SENDER) encoding:NSUTF8StringEncoding];
  112. NSString *message = @(messageCString);
  113. const char* secondsCString = asl_get( msg, ASL_KEY_TIME );
  114. const char* nanoCString = asl_get( msg, ASL_KEY_TIME_NSEC );
  115. NSTimeInterval seconds = secondsCString ? strtod(secondsCString, NULL) : [NSDate timeIntervalSinceReferenceDate] - NSTimeIntervalSince1970;
  116. double nanoSeconds = nanoCString? strtod(nanoCString, NULL) : 0;
  117. NSTimeInterval totalSeconds = seconds + (nanoSeconds / 1e9);
  118. NSDate *timeStamp = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
  119. DDLogMessage *logMessage = [[DDLogMessage alloc]initWithMessage:message
  120. level:_captureLevel
  121. flag:flag
  122. context:0
  123. file:@"DDASLLogCapture"
  124. function:0
  125. line:0
  126. tag:nil
  127. options:0
  128. timestamp:timeStamp];
  129. [DDLog log:async message:logMessage];
  130. }
  131. + (void)captureAslLogs {
  132. @autoreleasepool
  133. {
  134. /*
  135. We use ASL_KEY_MSG_ID to see each message once, but there's no
  136. obvious way to get the "next" ID. To bootstrap the process, we'll
  137. search by timestamp until we've seen a message.
  138. */
  139. struct timeval timeval = {
  140. .tv_sec = 0
  141. };
  142. gettimeofday(&timeval, NULL);
  143. unsigned long long startTime = timeval.tv_sec;
  144. __block unsigned long long lastSeenID = 0;
  145. /*
  146. syslogd posts kNotifyASLDBUpdate (com.apple.system.logger.message)
  147. through the notify API when it saves messages to the ASL database.
  148. There is some coalescing - currently it is sent at most twice per
  149. second - but there is no documented guarantee about this. In any
  150. case, there may be multiple messages per notification.
  151. Notify notifications don't carry any payload, so we need to search
  152. for the messages.
  153. */
  154. int notifyToken = 0; // Can be used to unregister with notify_cancel().
  155. notify_register_dispatch(kNotifyASLDBUpdate, &notifyToken, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(int token)
  156. {
  157. // At least one message has been posted; build a search query.
  158. @autoreleasepool
  159. {
  160. aslmsg query = asl_new(ASL_TYPE_QUERY);
  161. char stringValue[64];
  162. if (lastSeenID > 0) {
  163. snprintf(stringValue, sizeof stringValue, "%llu", lastSeenID);
  164. asl_set_query(query, ASL_KEY_MSG_ID, stringValue, ASL_QUERY_OP_GREATER | ASL_QUERY_OP_NUMERIC);
  165. } else {
  166. snprintf(stringValue, sizeof stringValue, "%llu", startTime);
  167. asl_set_query(query, ASL_KEY_TIME, stringValue, ASL_QUERY_OP_GREATER_EQUAL | ASL_QUERY_OP_NUMERIC);
  168. }
  169. [self configureAslQuery:query];
  170. // Iterate over new messages.
  171. aslmsg msg;
  172. aslresponse response = asl_search(NULL, query);
  173. while ((msg = dd_asl_next(response)))
  174. {
  175. [self aslMessageReceived:msg];
  176. // Keep track of which messages we've seen.
  177. lastSeenID = atoll(asl_get(msg, ASL_KEY_MSG_ID));
  178. }
  179. dd_asl_release(response);
  180. asl_free(query);
  181. if (_cancel) {
  182. notify_cancel(token);
  183. return;
  184. }
  185. }
  186. });
  187. }
  188. }
  189. @end