如何解决日志内容过大时控制台打印被截断的问题
======================

#### 问题现象

控制台日志输出内容被截断，后半部分无法打印。以下文日志为例（单个文本16个字符，一共拼接500次，累计8000字符），使用hilog进行打印时截断（只打印到第233次）。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/39/v3/4VE2ZXrtQR23b6GgeftrLA/zh-cn_image_0000002658914205.png?HW-CC-KV=V1&HW-CC-Date=20260709T133738Z&HW-CC-Expire=86400&HW-CC-Sign=E81E2A4049601DA8752D34549C3EA13B78FE9F2097D1D2FDFC00DCEE90509B3C "点击放大")

#### 背景知识

日志打印最多打印4096字节，超出限制文本将被截断，详见[约束与限制](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/hilog-guidelines-arkts#约束与限制)。

#### 解决方案

利用hilog封装log工具类检查日志长度，超出特定长度（比如：1024字节）就分段打印。

示例代码参考如下：

import hilog from '@ohos.hilog';
import { util } from '@kit.ArkTS';

class LogUtil {
  private static instance: LogUtil;
  private static DOMAIN: number = 0x0000;

  private constructor() {
    _// 私有构造函数，防止外部实例化_
  }

  public static getInstance(): LogUtil {
    if (!LogUtil.instance) {
      LogUtil.instance = new LogUtil();
    }
    return LogUtil.instance;
  }

  _// error、debug参照info即可_
  public info(logTag: string, content: string) {
    const maxSize = 1024;
    let textEncoder = new util.TextEncoder('utf-8');
    let result = textEncoder.encodeInto(content);
    if (result.byteLength <= maxSize) {
      _// 长度小于等于限制直接打印_
    } else {
      while (result.byteLength > maxSize) {
        _// 循环分段打印_
        let logContent = content.substring(0, maxSize);
        content = content.replace(logContent, '');
        hilog.info(LogUtil.DOMAIN, logTag, '%{public}s', logContent);
        _// 打印剩余日志_
      }
    }
    hilog.info(LogUtil.DOMAIN, logTag, '%{public}s', content);
  }
}

export default LogUtil;

@Entry
@Component
struct LongLogPrint {
  private oneContent: string = 'LongLogPrint';
  private logContent: string = '';

  aboutToAppear(): void {
    for (let i = 0; i < 500; i++) {
      this.logContent += this.oneContent + '\[' + i + '\],';
    }
  }

  build() {
    Row() {
      Column() {
        Button('Log Test')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            LogUtil.getInstance().info('Long Log', this.logContent);
          });
      }
      .width('100%');
    }
    .height('100%');
  }
}

修改后日志能打印完整：

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/b8/v3/im8Rk8h5TEWPu4XUO6dcCw/zh-cn_image_0000002658794253.png?HW-CC-KV=V1&HW-CC-Date=20260709T133738Z&HW-CC-Expire=86400&HW-CC-Sign=84034148824D07112840EB29DF85912483BE659779DC44393728359080DCC504 "点击放大")