1、鸿蒙hilog日志封装技巧

小技巧:鸿蒙封装hilog日志(避免日志泄露到安装包)

在鸿蒙客户端进行封装hilog日志打印时,使用DevEco Studio编译器打包,我们需要将日志过滤,可以简单进行如下操作,将开关设置false即可实现。

import hilog from '@ohos.hilog';
​
const LOGGER_PREFIX: string = 'HMTjBank';
​
class Logger {
  private domain: number;
  private prefix: string;
  // format Indicates the log format string.
  private format: string = '%{private}s, %{private}s'
  //打包关闭日志开关,设置false
  private isSetLog: boolean = true
​
  /**
   * constructor.
   *
   * @param prefix Identifies the log tag.
   * @param domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF
   * @param args Indicates the log parameters.
   */
  constructor(prefix: string = '', domain: number = 0xFF00) {
    this.prefix = prefix;
    this.domain = domain;
  }
​
  debug(...args: string[]): void {
    if (!this.isSetLog) {
      return
    }
    hilog.debug(this.domain, this.prefix, this.format, args);
  }
​
  info(...args: string[]): void {
    if (!this.isSetLog) {
      return
    }
    hilog.info(this.domain, this.prefix, this.format, args);
  }
​
  warn(...args: string[]): void {
    if (!this.isSetLog) {
      return
    }
    hilog.warn(this.domain, this.prefix, this.format, args);
  }
​
  error(...args: string[]): void {
    if (!this.isSetLog) {
      return
    }
    hilog.error(this.domain, this.prefix, this.format, args);
  }
}
​
export default new Logger(LOGGER_PREFIX, 0xFF02);

以上简单操作我们在打包时便不会将日志内容打印到hap或app安装包中,有效防止安全及隐私泄露,简洁高效!

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐