日志工具类
import hilog from '@ohos.hilog'
import { BusinessError } from '@kit.BasicServicesKit'
const LOGGER_DOMAIN: number = 0x0000
const LOGGER_TAG: string = 'HarmonyLogUtil'
export class LogUtil {
private static domain: number = LOGGER_DOMAIN
private static tag: string = LOGGER_TAG
private static format: string = '%{public}s'
private static isLoggingEnabled: boolean = true
static configure(domain: number = LOGGER_DOMAIN, tag: string = LOGGER_TAG, isLoggingEnabled: boolean = true): void {
LogUtil.domain = domain
LogUtil.tag = tag
LogUtil.isLoggingEnabled = isLoggingEnabled
}
static setDomain(domain: number): void {
LogUtil.domain = domain
}
static setTag(tag: string): void {
LogUtil.tag = tag
}
static setLoggingEnabled(isLoggingEnabled: boolean): void {
LogUtil.isLoggingEnabled = isLoggingEnabled
}
static debug(...messages: string[]): void {
if (LogUtil.isLoggingEnabled) {
hilog.debug(LogUtil.domain, LogUtil.tag, LogUtil.format.repeat(messages.length), ...messages)
}
}
static info(...messages: string[]): void {
if (LogUtil.isLoggingEnabled) {
hilog.info(LogUtil.domain, LogUtil.tag, LogUtil.format.repeat(messages.length), ...messages)
}
}
static warn(...messages: string[]): void {
if (LogUtil.isLoggingEnabled) {
hilog.warn(LogUtil.domain, LogUtil.tag, LogUtil.format.repeat(messages.length), ...messages)
}
}
static error(...messages: string[]): void {
if (LogUtil.isLoggingEnabled) {
const message = messages.join(' ')
hilog.error(LogUtil.domain, LogUtil.tag, `[ERROR]: ${message}`)
}
}
static fatal(...messages: string[]): void {
if (LogUtil.isLoggingEnabled) {
hilog.fatal(LogUtil.domain, LogUtil.tag, LogUtil.format.repeat(messages.length), ...messages)
}
}
static logJson(obj: object | string): void {
try {
let formattedJson: string
if (typeof obj === 'string') {
const parsedObj = JSON.parse(obj) as object
formattedJson = JSON.stringify(parsedObj, null, 2)
} else {
formattedJson = JSON.stringify(obj, null, 2)
}
formattedJson.split('\n').forEach(line => console.debug(line))
} catch (err) {
LogUtil.error(JSON.stringify(err))
}
}
}
export default LogUtil