目录

鸿蒙封装日志工具类-ohos.hilog打印日志

【鸿蒙】封装日志工具类 ohos.hilog打印日志

封装一个ohos.hilog打印日志

首先要了解hilog四大日志类型: info、debug、warm、error

方法中四个参数的作用

**domain: number

tag: string

format: string

…args: any[ ]**

实例:

https://i-blog.csdnimg.cn/img_convert/b7df1aecce2621f5b5db6b246c10cae6.png

//普通的info日志,使用info方法来打印

//第一个参数 : 0x0000 表示当前日志的域为0

//第二个参数 : 表示此系统的日志过滤关键字为 mylog,可以在deveco的日志面板中去过滤查看

//第三个参数 : %{public}s 表示以明文的形式来显示字符串日志

//第四个及其以后的参数 : 表示要打印的日志

testTag 表示日志输出的关键字

https://i-blog.csdnimg.cn/img_convert/a6964fa274c5b536516d850e3124bef3.png

https://i-blog.csdnimg.cn/img_convert/85955663b67e6fd1d1207b99e4000fe5.png

%{public } s    s指的是String 表示后面是以字符串的格式输出的

意思是 这个是以明文形式字符串输出

public 私有的 加密写死的

https://i-blog.csdnimg.cn/img_convert/157e62e02ba7e72117586e7422345e68.png

封装项目日志文件 :common/utils/Logger.ets

日志类的封装思路:

使用类的静态方法进行封装四个方法

导出这个类

https://i-blog.csdnimg.cn/direct/669ac622c1684fe5816ef5bf1a545d04.png

import  { hilog }  from  '@kit.PerformanceAnalysisKit'

const domain =0x0000
const tag ='mylog'
const format ='%{public}s %{public}s'

// 按需导出
export class Logger {
static info(...args: string[ ]){
 hilog.info(domain,tag,format, ...args)
}
static debug(...args: string[]){
hilog.debug(domain, tag,format,...args)
}
static warn(...args: string[]){
hilog.warn(domain,tag,format,...args)
}
static error(...args: string[]){
hilog.error(domain,tag,format, ...args)
}
}

用的时候 直接导入即可

https://i-blog.csdnimg.cn/img_convert/42f81da96571c89a403f6f54eb8df6e1.png

https://i-blog.csdnimg.cn/img_convert/62488f8ebc47d8d4e127cb27f8f236bb.png

https://i-blog.csdnimg.cn/direct/0de4db981bdd422c9f7984cec1e428ec.png