如何在 Objective-C 中挂钩 Apple 的 `os_log_with_type` 方法

How to hook Apple's `os_log_with_type` method in Objective-C

我想挂钩“React Native”RCTLog 日志方法_RCTLogJavaScriptInternal ,源代码是:

void _RCTLogJavaScriptInternal(RCTLogLevel level, NSString *message)
{
  RCTLogFunction logFunction = RCTGetLocalLogFunction();
  BOOL log = RCT_DEBUG || (logFunction != nil);
  if (log && level >= RCTGetLogThreshold()) {
    if (logFunction) {
      logFunction(level, RCTLogSourceJavaScript, nil, nil, message);
    }
  }
}

RCTLogFunction RCTDefaultLogFunction =
    ^(RCTLogLevel level,
      RCTLogSource source,
      __unused NSString *fileName,
      __unused NSNumber *lineNumber,
      NSString *message) {
      os_log_with_type(RCTLogForLogSource(source), RCTLogTypeForLogLevel(level), "%{public}s", message.UTF8String);
    };

因此,如果我只是挂钩 Apple 的 os_log_with_type,我将获得 RCTLog 日志。 这是我的代码,但不起作用。请帮我。谢谢!!!

#import <os/log.h>
#import "fishhook.h"

static void (*original_oslog)((os_log_t log, os_log_type_t type, const char *format, ...));

void hook_oslog(os_log_t log, os_log_type_t type, const char *format, ...) {
    NSLog(@"hook success!");
}

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        struct rebinding oslog_rebinding = { "os_log_with_type", hook_oslog, (void *)&original_oslog };
        rebind_symbols((struct rebinding[1]){oslog_rebinding}, 1);
    });
}

最后,我找到了解决办法。不用hook,相关的API已经被React Native提供了。

RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
  NSLog(@"%@", message);
});