HarmonyOS 鸿蒙Next Log区域的“优雅输出” - 封装hilog为Logger
HarmonyOS 鸿蒙Next Log区域的“优雅输出” - 封装hilog为Logger 一、前言
鸿蒙为我们提供了日志输出方法:hilog。hilog固然好用,能够保证我们查看Log的时候,格式完整,结果清晰。然而如果每次写hilog都要一行一行写重复的domain、prefix等字段,好像又有点麻烦,那么为了解决这个问题,让我们来自己封装一个Logger对象,实现hilog的优雅输出吧~
二、Logger - “优雅输出”
1、代码展示:
import hilog from '@ohos.hilog';
class Logger {
private domain: number;
private prefix: string;
private format: string = '[%{public}s] %{public}s, %{public}s';//TAG method msg
/**
* constructor.
*
* @param Prefix Identifies the log tag.
* @param domain Domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF.
*/
constructor(prefix: string = 'Xiang', domain: number = 0xFF00) {
this.prefix = prefix;
this.domain = domain;
}
debug(...args: string[]): void {
hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: string[]): void {
hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: string[]): void {
hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: string[]): void {
hilog.error(this.domain, this.prefix, this.format, args);
}
d(...args: string[]): void {
hilog.debug(this.domain, this.prefix, this.format, args);
}
i(...args: string[]): void {
hilog.info(this.domain, this.prefix, this.format, args);
}
w(...args: string[]): void {
hilog.warn(this.domain, this.prefix, this.format, args);
}
e(...args: string[]): void {
hilog.error(this.domain, this.prefix, this.format, args);
}
}
// 这里的prefix和domain字段,可以根据个人喜好来修改
export default new Logger('Xiang', 0xFF00)
2、使用示例:
import Logger from '../../utils/Logger'; //Logger所在目录
class Test {
private TAG = "NetworkUtil";
constructor {
Logger.d(this.TAG, "constructor", "~~~~~~~~");
}
}
3、输出展示:
希望对大家有所帮助,如果有小伙伴觉得还不错的话,辛苦点个赞赞哟~
更多关于HarmonyOS 鸿蒙Next Log区域的“优雅输出” - 封装hilog为Logger的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS 鸿蒙Next Log区域的“优雅输出” - 封装hilog为Logger的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS中,hilog
是用于日志记录的系统API。为了实现日志的“优雅输出”,可以通过封装hilog
为Logger
类来简化日志调用,提升代码可读性和可维护性。封装后的Logger
类可以提供统一的日志接口,支持不同日志级别(如DEBUG、INFO、WARN、ERROR等),并允许自定义日志格式和输出位置。封装过程中,可以结合鸿蒙的hilog
API,确保日志输出符合系统要求,同时简化开发者的日志调用方式。封装后的Logger
类可以通过单例模式或静态方法提供全局日志服务,方便在应用的不同模块中使用。