鸿蒙开发5.0【日志打印】运维

日志打印

介绍

本示例使用hilog日志系统,提供日志打印类,使应用/服务可以按照指定级别、标识和格式字符串输出日志内容,帮助开发者了解应用/服务的运行状态,更好地调试程序。

效果预览

1

使用说明:

1.进入应用会自动生成一个空的日志文件。

2.点击log按钮即可输出日志,并将日志生成到日志文件当中。

具体实现

  • 日志输出功能封装在Logger,源码参考:[Logger.ets]:
/*
 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { Configure } from './Configure';
import { LogLevel } from './LogLevel';
import { LoggerModel } from './LoggerModel';
import { hilog } from '@kit.PerformanceAnalysisKit';

interface ILoggerStrategy {
  debug(message: string): void

  info(message: string): void

  warn(message: string): void

  error(message: string): void

  fatal(message: string): void
}

class ConsoleLoggerStrategy implements ILoggerStrategy {
  private configure: Configure;
  private domain: number;

  constructor(configure: Configure) {
    this.configure = configure;
    this.domain = 0xFF00;
  }

  public debug(message: string): void {
    hilog.debug(this.domain, this.configure.defaults.appenders, message);
  }

  public info(message: string): void {
    hilog.info(this.domain, this.configure.defaults.appenders, message);
  }

  public warn(message: string): void {
    hilog.warn(this.domain, this.configure.defaults.appenders, message);
  }

  public error(message: string): void {
    hilog.error(this.domain, this.configure.defaults.appenders, message);
  }

  public fatal(message: string): void {
    hilog.fatal(this.domain, this.configure.defaults.appenders, message);
  }
}

class HilogLoggerStrategy implements ILoggerStrategy {
  private configure: Configure;
  private loggerModel: LoggerModel;

  constructor(configure: Configure) {
    this.configure = configure;
    this.loggerModel = new LoggerModel(`${configure.defaults.appenders}`);
  }

  public debug(message: string): void {
    this.loggerModel.debug(`[DEBUG] ${this.configure.defaults.appenders} - `, `${message}`);
  }

  public info(message: string): void {
    this.loggerModel.info(`[INFO] ${this.configure.defaults.appenders} - `, `${message}`);
  }

  public warn(message: string): void {
    this.loggerModel.warn(`[WARN] ${this.configure.defaults.appenders} - `, `${message}`);
  }

  public error(message: string): void {
    this.loggerModel.error(`[ERROR] ${this.configure.defaults.appenders} - `, `${message}`);
  }

  public fatal(message: string): void {
    this.loggerModel.fatal(`[FATAL] ${this.configure.defaults.appenders} - `, `${message}`);
  }
}

class FileLoggerStrategy implements ILoggerStrategy {
  private fd: number = 0;
  private configure: Configure;
  private fileStream?: fileIo.File;

  constructor(configure: Configure, context: common.UIAbilityContext) {
    // 初始化文件
    this.configure = configure;
    let path = context.filesDir;
    let result = `${path}/${this.configure.cheese.filename}`;
    try {
      this.fileStream = fileIo.openSync(result, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      this.fd = this.fileStream.fd;
    } catch (err) {
      return;
    }
  }

  private async writeFile(message: string) {
    // 写文件
    fileIo.writeSync(this.fd, `${message}\n`);
    // fs.closeSync(this.fileStream)
    // this.fileStream.closeSync()
  }

  public async debug(message: string): Promise<void> {
    await this.writeFile(`[DEBUG] ${this.configure.defaults.appenders}, ${message}`);
  }

  public async info(message: string): Promise<void> {
    await this.writeFile(`[INFO] ${this.configure.defaults.appenders}, ${message}`);
  }

  public async warn(message: string): Promise<void> {
    await this.writeFile(`[WARN] ${this.configure.defaults.appenders}, ${message}`);
  }

  public async error(message: string): Promise<void> {
    await this.writeFile(`[ERROR] ${this.configure.defaults.appenders}, ${message}`);
  }

  public async fatal(message: string): Promise<void> {
    await this.writeFile(`[FATAL] ${this.configure.defaults.appenders}, ${message}`);
  }
}


export class Logger {
  private configure = new Configure([''], '', '', LogLevel.DEBUG);
  private loggerModel: LoggerModel = new LoggerModel(`${this.configure.defaults.appenders}`);
  private strategies: Map<string, ILoggerStrategy> = new Map();
  private context: common.UIAbilityContext;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  public setConfigure(configure: Configure) {
    this.strategies = new Map();
    this.configure = configure;
    this.loggerModel = new LoggerModel(`${configure.defaults.appenders}`);
    if (!configure || !configure.cheese || !configure.cheese.types) {
      return;
    }
    if (configure.cheese.types.includes('file')) {
      this.strategies.set('file', new FileLoggerStrategy(configure, this.context));
    }
    if (configure.cheese.types.includes('hilog')) {
      this.strategies.set('hilog', new HilogLoggerStrategy(configure));
    }

    if (configure.cheese.types.includes('console') || this.strategies.size <= 0) {
      this.strategies.set('console', new ConsoleLoggerStrategy(configure));
    }
  }

  public debug(message: string): void {
    let levelCheck = this.loggerModel.isLoggable(this.configure.defaults.appenders, LogLevel.DEBUG);
    if (levelCheck && this.configure.defaults.level <= LogLevel.DEBUG) {
      this.strategies.forEach((value, key) => {
        this.strategies?.get(key)?.debug(message);
      })
    }
  }

  public info(message: string): void {
    let levelCheck = this.loggerModel.isLoggable(message, LogLevel.INFO);
    if (levelCheck && this.configure.defaults.level <= LogLevel.INFO) {
      this.strategies.forEach((value, key) => {
        this.strategies?.get(key)?.info(message);
      })
    }
  }

  public warn(message: string): void {
    let levelCheck = this.loggerModel.isLoggable(message, LogLevel.WARN);
    if (levelCheck && this.configure.defaults.level <= LogLevel.WARN) {
      this.strategies.forEach((value, key) => {
        this.strategies.get(key)?.warn(message);
      })
    }
  }

  public error(message: string): void {
    let levelCheck = this.loggerModel.isLoggable(message, LogLevel.ERROR);
    if (levelCheck && this.configure.defaults.level <= LogLevel.ERROR) {
      this.strategies.forEach((value, key) => {
        this.strategies.get(key)?.error(message);
      })
    }
  }

  public fatal(message: string): void {
    let levelCheck = this.loggerModel.isLoggable(message, LogLevel.FATAL);
    if (levelCheck && this.configure.defaults.level <= LogLevel.FATAL) {
      this.strategies.forEach((value, key) => {
        this.strategies.get(key)?.fatal(message);
      })
    }
  }
}
  • 日志输出:Logger类根据Configure的types参数将日志分为三个类型,其中file类型会将日志写入本地文件,console类型调用ConsoleLoggerStrategy类输出,hilog类型调用HilogLoggerStrategy类输出;
  • 日志文件写入本地:FileLoggerStrategy类使用@ohos.file.fs将日志写入本地文件中,本示例只是展示了文件写入文件操作的使用方法,在实战场景中,建议把耗时操作放入子线程中运行。

以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
1

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下

内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!

鸿蒙【北向应用开发+南向系统层开发】文档

鸿蒙【基础+实战项目】视频

鸿蒙面经

在这里插入图片描述

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值