问题详情
Native侧引用的三方库使用printf等方法打印到stdout、stderr的信息怎么获取?在三方库代码里有许多fprintf, std::cont printf 的标准日志打印log,在程序开发中无法查看这些日志。
解决措施
cout/printf是语言提供的打印函数,并不能填充到hilog日志中。可通过重定向的方法将日志打印到文件来获取打印信息。具体方法如下:
Native侧重定向方法主体。
#include "napi/native_api.h"
#include <hilog/log.h>
#include <string>
#include "iostream"
#include "fstream"
#define LOG_TAG "Pure"
static napi_value Redirect(napi_env env, napi_callback_info info) {
// 获取函数的JS参数
size_t argc = 1;
napi_value argv[1] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
// 解析参数1,保存文件的目标目录
size_t targetDirectoryNameSize;
char targetDirectoryNameBuf[512];
napi_get_value_string_utf8(env, argv[0], targetDirectoryNameBuf, sizeof(targetDirectoryNameBuf),
&targetDirectoryNameSize);
std::string targetDirectoryName(targetDirectoryNameBuf, targetDirectoryNameSize); // 目标目录
OH_LOG_INFO(LOG_APP, "C++侧收到的目标路径 === %{public}s", targetDirectoryNameBuf);
std::string targetSandboxPath = targetDirectoryName + "/Log.log"; // 存入的文件路径
// 使用freopen函数把文件关联到标准输出
FILE *stdoutFile = NULL;
FILE *stderrFile = NULL;
stdoutFile = freopen(targetSandboxPath.c_str(), "a", stdout);
stderrFile = freopen(targetSandboxPath.c_str(), "a", stderr);
if (NULL == stdoutFile || NULL == stderrFile) {
OH_LOG_INFO(LOG_APP, "重创建!");
// 打开沙箱文件的文件输出流,会创建出一个文件
std::ofstream outputFile(targetSandboxPath, std::ios::binary);
if (!outputFile) {
OH_LOG_ERROR(LOG_APP, "无法创建目标文件!");
return nullptr;
}
stdoutFile = freopen(targetSandboxPath.c_str(), "a", stdout);
stderrFile = freopen(targetSandboxPath.c_str(), "a", stderr);
if (NULL == stdoutFile || NULL == stderrFile) {
OH_LOG_ERROR(LOG_APP, "失败!");
return nullptr;
}
}
OH_LOG_WARN(LOG_APP, "重定向!");
printf("\n*****************redirect分割线*****************\n");
return 0;
}
ArkTS侧调用并传入路径信息。
在EntryAbility的onCreate()方法中调用重定向。
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
let file : string = this.context.getApplicationContext().filesDir;
testNapi.redirect(file);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
}