鸿蒙5.0开发常见问题【如何获取Native侧printf等方法打印的信息?】

问题详情

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'); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值