DDASLLogCapture.m 7.3 KB

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