HarmonyOS 鸿蒙Next中Native侧如何使hilog日志保存到文件中

HarmonyOS 鸿蒙Next中Native侧如何使hilog日志保存到文件中 使用HiLog打印默认是打印在控制台上,默认未将日志落盘到本地,如果在现网出现问题,则没有任何问题时的日志,从而无法定位问题。Native侧的hilog日志可以保存到文件中嘛

4 回复

在ArkTS侧将沙箱中的路径传递给Native侧,通过OpenFile方法打开文件,然后调用MyHiLog方法把日志写入到文件中。示例代码如下:

index.ets:在ArkTS侧获取到沙箱路径,将沙箱中的路径传递给Native侧。

import { hilog } from '@kit.PerformanceAnalysisKit';
import testNapi from 'libentry.so';

const DOMAIN = 0x0000;

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  aboutToAppear(): void {
    let path: string = getContext(this).filesDir
    testNapi.init(path);
  }

  build() {
    Row() {
      Column() {
        Button("test")
          .fontSize($r('app.float.page_text_font_size'))
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            hilog.info(DOMAIN, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.add(2, 3));
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

Init函数:Native层从ArkTS层获取到的日志路径存放到static变量m_path中,作为日志全局的路径。设置m_openState来防止重复初始化,通过函数OpenFile来打开/创建日志文件。如果正常打开文件则使用OH_LOG_SetCallback来注册日志落盘函数。否则返回异常,ArkTS通过返回值来判断是否初始化成功。

static napi_value Init(napi_env env, napi_callback_info info)
{
    size_t argc = 1;
    napi_value args[1] = {nullptr};
    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
    
    char path[1024 * 4] = {0};
    size_t pathLen = 0;
    napi_get_value_string_utf8(env, args[0], path, 1024 * 4, &pathLen);
    
    int ret = 0;
    // 1.设置打印文件路径&日志文件
    std::string tmpPath(path);
    m_path = tmpPath;
    OH_LOG_INFO(LOG_APP, "napi sum Init m_path: %{public}s, %{public}d", m_path.c_str(), m_path.size());
    if (m_openState == UNOPENED && m_path != "" && (m_file = OpenFile("ab"))) {
        m_openState = OPEN;
        // 2.注册回调接口
        OH_LOG_SetCallback(MyHiLog);
    } else {
        ret = -1;
        OH_LOG_INFO(LOG_APP, "napi sum Init m_path fail:%{public}d| %{public}s, %{public}d", m_openState , m_path.c_str(), m_path.size());
    }
    
    napi_value returnValue;
    napi_create_int32(env, ret, &returnValue);
    return returnValue;
}

OpenFile函数:使用realpath函数来获取文件的绝对路径,并判断路径是否可用,如可用则使用fopen带参数"ab"来打开该文件,并获取到句柄存储到m_file静态变量中。

FILE *OpenFile(const char *pszMode)
{
    char filePath[PATH_MAX] = {0};
    char *ret = realpath(m_path.c_str(), filePath);
    if (ret == nullptr) {
        OH_LOG_INFO(LOG_APP, "napi sum OpenFile path realpath fail!!, %{public}s, %{public}d", m_path.c_str(), m_path.size());
        return nullptr;
    }
    std::string fullFileName = std::string(filePath) + "/test.log";
    OH_LOG_INFO(LOG_APP, "napi sum OpenFile path is:%{public}s", fullFileName.c_str());
    return std::fopen(fullFileName.c_str(), pszMode);
}

回调函数MyHiLog:判断文件句柄m_file是否正常,正常则可以使用fwrite和fflush来写入到文件中。

void MyHiLog(const LogType type, const LogLevel level, const unsigned int domain, const char *tag, const char *msg)
{
    if (m_file != nullptr) {
        std::string tmp(msg);
        tmp += '\n';
        fwrite(tmp.c_str(), sizeof(char), tmp.size(), m_file);
        fflush(m_file);
    }
}

Add函数:ArkTS侧调用Add方法,Add方法内输出日志。

static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);
    OH_LOG_INFO(LOG_APP, "napi sum is:%{public}d.", (int)(value0 + value1));

    return sum;
}

更多关于HarmonyOS 鸿蒙Next中Native侧如何使hilog日志保存到文件中的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


能否给个完整的demo,这么复杂的代码根本看不懂。要简单方便的组件那种~~,

在鸿蒙Next中,Native侧使用hilog日志保存到文件需配置hilog的persistence模块。具体步骤:

  1. 在config.json中声明"hilog_persistent"能力;
  2. 调用hilog的C++接口设置持久化参数,包括日志级别、文件路径和大小限制;
  3. 使用HiLogLabel初始化日志标签时指定domain和tag。

日志将自动按配置写入指定文件,文件路径通常为/data/log/hilog/。需注意文件系统权限问题。

在HarmonyOS Next中,Native侧的HiLog日志确实可以通过配置实现落盘保存。以下是具体实现方法:

  1. 使用hilog的persist模式: 在代码中调用HiLog的持久化接口:
#include <hilog/log.h>
HiLogPersist(LOG_APP, LOG_INFO, 0xD000F00, "TAG", "This log will be persisted");
  1. 通过hilog命令行工具配置:
hilog -p start  # 开启持久化模式
hilog -s 1024  # 设置日志缓冲区大小(KB)
  1. 日志文件默认存储路径: /data/log/hilog/

注意事项:

  • 需要申请ohos.permission.READ_LOGS权限
  • 持久化日志会占用存储空间,建议按需开启
  • 可通过hilog -p stop关闭持久化
  • 日志文件会自动轮转,默认保留7天

对于现网问题定位,建议在关键路径添加持久化日志,并合理控制日志级别和数量。

回到顶部