DDASLLogCapture.m 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2018, 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. #if !TARGET_OS_WATCH
  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. @implementation DDASLLogCapture
  28. + (void)start {
  29. // Ignore subsequent calls
  30. if (!_cancel) {
  31. return;
  32. }
  33. _cancel = NO;
  34. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  35. [self captureAslLogs];
  36. });
  37. }
  38. + (void)stop {
  39. _cancel = YES;
  40. }
  41. + (DDLogLevel)captureLevel {
  42. return _captureLevel;
  43. }
  44. + (void)setCaptureLevel:(DDLogLevel)level {
  45. _captureLevel = level;
  46. }
  47. #pragma mark - Private methods
  48. + (void)configureAslQuery:(aslmsg)query {
  49. const char param[] = "7"; // ASL_LEVEL_DEBUG, which is everything. We'll rely on regular DDlog log level to filter
  50. asl_set_query(query, ASL_KEY_LEVEL, param, ASL_QUERY_OP_LESS_EQUAL | ASL_QUERY_OP_NUMERIC);
  51. // Don't retrieve logs from our own DDASLLogger
  52. asl_set_query(query, kDDASLKeyDDLog, kDDASLDDLogValue, ASL_QUERY_OP_NOT_EQUAL);
  53. #if !TARGET_OS_IPHONE || (defined(TARGET_SIMULATOR) && TARGET_SIMULATOR)
  54. int processId = [[NSProcessInfo processInfo] processIdentifier];
  55. char pid[16];
  56. sprintf(pid, "%d", processId);
  57. asl_set_query(query, ASL_KEY_PID, pid, ASL_QUERY_OP_EQUAL | ASL_QUERY_OP_NUMERIC);
  58. #endif
  59. }
  60. + (void)aslMessageReceived:(aslmsg)msg {
  61. const char* messageCString = asl_get( msg, ASL_KEY_MSG );
  62. if ( messageCString == NULL )
  63. return;
  64. DDLogFlag flag;
  65. BOOL async;
  66. const char* levelCString = asl_get(msg, ASL_KEY_LEVEL);
  67. switch (levelCString? atoi(levelCString) : 0) {
  68. // By default all NSLog's with a ASL_LEVEL_WARNING level
  69. case ASL_LEVEL_EMERG :
  70. case ASL_LEVEL_ALERT :
  71. case ASL_LEVEL_CRIT : flag = DDLogFlagError; async = NO; break;
  72. case ASL_LEVEL_ERR : flag = DDLogFlagWarning; async = YES; break;
  73. case ASL_LEVEL_WARNING : flag = DDLogFlagInfo; async = YES; break;
  74. case ASL_LEVEL_NOTICE : flag = DDLogFlagDebug; async = YES; break;
  75. case ASL_LEVEL_INFO :
  76. case ASL_LEVEL_DEBUG :
  77. default : flag = DDLogFlagVerbose; async = YES; break;
  78. }
  79. if (!(_captureLevel & flag)) {
  80. return;
  81. }
  82. // NSString * sender = [NSString stringWithCString:asl_get(msg, ASL_KEY_SENDER) encoding:NSUTF8StringEncoding];
  83. NSString *message = @(messageCString);
  84. const char* secondsCString = asl_get( msg, ASL_KEY_TIME );
  85. const char* nanoCString = asl_get( msg, ASL_KEY_TIME_NSEC );
  86. NSTimeInterval seconds = secondsCString ? strtod(secondsCString, NULL) : [NSDate timeIntervalSinceReferenceDate] - NSTimeIntervalSince1970;
  87. double nanoSeconds = nanoCString? strtod(nanoCString, NULL) : 0;
  88. NSTimeInterval totalSeconds = seconds + (nanoSeconds / 1e9);
  89. NSDate *timeStamp = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
  90. DDLogMessage *logMessage = [[DDLogMessage alloc]initWithMessage:message
  91. level:_captureLevel
  92. flag:flag
  93. context:0
  94. file:@"DDASLLogCapture"
  95. function:nil
  96. line:0
  97. tag:nil
  98. options:0
  99. timestamp:timeStamp];
  100. [DDLog log:async message:logMessage];
  101. }
  102. + (void)captureAslLogs {
  103. @autoreleasepool
  104. {
  105. /*
  106. We use ASL_KEY_MSG_ID to see each message once, but there's no
  107. obvious way to get the "next" ID. To bootstrap the process, we'll
  108. search by timestamp until we've seen a message.
  109. */
  110. struct timeval timeval = {
  111. .tv_sec = 0
  112. };
  113. gettimeofday(&timeval, NULL);
  114. unsigned long long startTime = (unsigned long long)timeval.tv_sec;
  115. __block unsigned long long lastSeenID = 0;
  116. /*
  117. syslogd posts kNotifyASLDBUpdate (com.apple.system.logger.message)
  118. through the notify API when it saves messages to the ASL database.
  119. There is some coalescing - currently it is sent at most twice per
  120. second - but there is no documented guarantee about this. In any
  121. case, there may be multiple messages per notification.
  122. Notify notifications don't carry any payload, so we need to search
  123. for the messages.
  124. */
  125. int notifyToken = 0; // Can be used to unregister with notify_cancel().
  126. notify_register_dispatch(kNotifyASLDBUpdate, &notifyToken, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(int token)
  127. {
  128. // At least one message has been posted; build a search query.
  129. @autoreleasepool
  130. {
  131. aslmsg query = asl_new(ASL_TYPE_QUERY);
  132. char stringValue[64];
  133. if (lastSeenID > 0) {
  134. snprintf(stringValue, sizeof stringValue, "%llu", lastSeenID);
  135. asl_set_query(query, ASL_KEY_MSG_ID, stringValue, ASL_QUERY_OP_GREATER | ASL_QUERY_OP_NUMERIC);
  136. } else {
  137. snprintf(stringValue, sizeof stringValue, "%llu", startTime);
  138. asl_set_query(query, ASL_KEY_TIME, stringValue, ASL_QUERY_OP_GREATER_EQUAL | ASL_QUERY_OP_NUMERIC);
  139. }
  140. [self configureAslQuery:query];
  141. // Iterate over new messages.
  142. aslmsg msg;
  143. aslresponse response = asl_search(NULL, query);
  144. while ((msg = asl_next(response)))
  145. {
  146. [self aslMessageReceived:msg];
  147. // Keep track of which messages we've seen.
  148. lastSeenID = (unsigned long long)atoll(asl_get(msg, ASL_KEY_MSG_ID));
  149. }
  150. asl_release(response);
  151. asl_free(query);
  152. if (_cancel) {
  153. notify_cancel(token);
  154. return;
  155. }
  156. }
  157. });
  158. }
  159. }
  160. @end
  161. #endif