鴻蒙NEXT開發日志工具類(ArkTs)

import hilog from '@ohos.hilog';
import { JSON } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { StrUtil } from './StrUtil';/*** 日志工具類* author: 鴻蒙布道師* since: 2024/03/31*/
export class LogUtil {private static logSize: number = 2048;private static domain: number = 0x0000;private static tag: string = 'HarmonyUtilsLog'; // 日志Tagprivate static showLog: boolean = true; // 是否顯示打印日志private static isHilog: boolean = true; // true-hilog、false-console/*** 初始化日志參數(該方法建議在Ability里調用)* @param domain - 領域標識* @param tag - 日志標簽* @param showLog - 是否顯示日志* @param isHilog - 是否使用hilog*/static init(domain: number = LogUtil.domain, tag: string = LogUtil.tag, showLog: boolean = true,isHilog: boolean = true): void {LogUtil.domain = domain;LogUtil.tag = tag;LogUtil.showLog = showLog;LogUtil.isHilog = isHilog;}/*** 設置領域標識* @param domain - 領域標識*/static setDomain(domain: number = LogUtil.domain): void {LogUtil.domain = domain;}/*** 設置日志標簽* @param tag - 日志標簽*/static setTag(tag: string = LogUtil.tag): void {LogUtil.tag = tag;}/*** 設置是否顯示日志* @param showLog - 是否顯示日志*/static setShowLog(showLog: boolean = true): void {LogUtil.showLog = showLog;}/*** 設置日志打印方式* @param isHilog - true-hilog、false-console*/static setHilog(isHilog: boolean): void {LogUtil.isHilog = isHilog;}/*** 打印DEBUG級別日志* @param args - 日志內容*/static debug(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.DEBUG);}/*** 打印INFO級別日志* @param args - 日志內容*/static info(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.INFO);}/*** 打印WARN級別日志* @param args - 日志內容*/static warn(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.WARN);}/*** 打印ERROR級別日志* @param args - 日志內容*/static error(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.ERROR);}/*** 打印FATAL級別日志* @param args - 日志內容*/static fatal(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.FATAL);}/*** 打印JSON對象或JSON字符串* @param msg - JSON對象或字符串*/static print(msg: object | string): void {try {const content = LogUtil.formatMessage(msg);const len = Math.ceil(content.length / LogUtil.logSize);for (let i = 0; i < len; i++) {const end = Math.min((i + 1) * LogUtil.logSize, content.length);const logMsg = `\n${content.substring(i * LogUtil.logSize, end)}`;LogUtil.levelLog(logMsg, hilog.LogLevel.DEBUG);}} catch (err) {const error = err as BusinessError;console.error(`LogUtil-print-異常 ~ code: ${error.code} -·- message: ${error.message}`);}}/*** 統一日志輸出* @param message - 日志內容* @param level - 日志級別*/private static uniLog(message: (string | object)[], level: hilog.LogLevel): void {if (!LogUtil.showLog) return;const topLine = LogUtil.getLine(LogUtil.tag);LogUtil.levelLog(topLine, level);if (level === hilog.LogLevel.ERROR) {const locationLog = LogUtil.getLogLocation();LogUtil.levelLog(locationLog, level);}const content = LogUtil.formatMessage(message);const len = Math.ceil(content.length / LogUtil.logSize);for (let i = 0; i < len; i++) {const end = Math.min((i + 1) * LogUtil.logSize, content.length);const logMsg = `\n|  ${content.substring(i * LogUtil.logSize, end)}`;LogUtil.levelLog(logMsg, level);}const bottomLine = LogUtil.getLine('');LogUtil.levelLog(bottomLine, level);}/*** 格式化日志內容* @param message - 日志內容,可以是字符串、對象或數組*/private static formatMessage(message: (string | object)[] | object | string): string {let logMessage = '';// Handle array inputif (Array.isArray(message)) {message.forEach((msg: string | object) => {logMessage += typeof msg === 'object' ? LogUtil.getObjectToJson(msg) : String(msg);});}// Handle object inputelse if (typeof message === 'object') {logMessage = LogUtil.getObjectToJson(message);}// Handle string inputelse {logMessage = String(message);}return logMessage;}/*** 對象轉JSON字符串* @param obj - 對象* @param line - 是否格式化換行*/private static getObjectToJson(obj: object, line: boolean = true): string {try {let jsonStr = JSON.stringify(obj, null, 2);if (line) {jsonStr = jsonStr.replace(/\n/g, '\n|\t');jsonStr = jsonStr.replace(/..$/, '  ');}return jsonStr;} catch {return '';}}/*** 獲取代碼位置*/private static getLogLocation(): string {const stackArray = new Error().stack?.split('\n').filter(item => item.trim() !== '').splice(-2) ?? [];const errorLocation = stackArray.join('\n').replace(/\s+/g, '');return `\n|  ${errorLocation}`;}/*** 獲取生成的日志邊框* @param tag - 日志標簽* @param length - 邊框長度*/private static getLine(tag: string = '', length: number = 160): string {if (StrUtil.isNotEmpty(tag)) {return `┌${StrUtil.repeat('─', 10)} ${tag} ${StrUtil.repeat('─', length - tag.length - 2)}`;}return `└${StrUtil.repeat('─', 10)}${StrUtil.repeat('─', length)}`;}/*** 日志打印* @param msg - 日志內容* @param level - 日志級別*/private static levelLog(msg: string, level: hilog.LogLevel): void {if (LogUtil.isHilog) {// Explicitly call the appropriate hilog method based on the log levelswitch (level) {case hilog.LogLevel.DEBUG:hilog.debug(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.INFO:hilog.info(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.WARN:hilog.warn(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.ERROR:hilog.error(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.FATAL:hilog.fatal(LogUtil.domain, LogUtil.tag, msg);break;default:console.error(`Unsupported log level: ${level}`);break;}} else {// Fallback to console logging if hilog is not enabledswitch (level) {case hilog.LogLevel.DEBUG:console.debug(msg);break;case hilog.LogLevel.INFO:console.info(msg);break;case hilog.LogLevel.WARN:console.warn(msg);break;case hilog.LogLevel.ERROR:console.error(msg);break;case hilog.LogLevel.FATAL:console.log(msg);break;default:console.error(`Unsupported log level: ${level}`);break;}}}
}代碼如下:

import hilog from '@ohos.hilog';
import { JSON } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { StrUtil } from './StrUtil';/*** 日志工具類* author: 鴻蒙布道師* since: 2024/03/31*/
export class LogUtil {private static logSize: number = 2048;private static domain: number = 0x0000;private static tag: string = 'HarmonyUtilsLog'; // 日志Tagprivate static showLog: boolean = true; // 是否顯示打印日志private static isHilog: boolean = true; // true-hilog、false-console/*** 初始化日志參數(該方法建議在Ability里調用)* @param domain - 領域標識* @param tag - 日志標簽* @param showLog - 是否顯示日志* @param isHilog - 是否使用hilog*/static init(domain: number = LogUtil.domain, tag: string = LogUtil.tag, showLog: boolean = true,isHilog: boolean = true): void {LogUtil.domain = domain;LogUtil.tag = tag;LogUtil.showLog = showLog;LogUtil.isHilog = isHilog;}/*** 設置領域標識* @param domain - 領域標識*/static setDomain(domain: number = LogUtil.domain): void {LogUtil.domain = domain;}/*** 設置日志標簽* @param tag - 日志標簽*/static setTag(tag: string = LogUtil.tag): void {LogUtil.tag = tag;}/*** 設置是否顯示日志* @param showLog - 是否顯示日志*/static setShowLog(showLog: boolean = true): void {LogUtil.showLog = showLog;}/*** 設置日志打印方式* @param isHilog - true-hilog、false-console*/static setHilog(isHilog: boolean): void {LogUtil.isHilog = isHilog;}/*** 打印DEBUG級別日志* @param args - 日志內容*/static debug(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.DEBUG);}/*** 打印INFO級別日志* @param args - 日志內容*/static info(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.INFO);}/*** 打印WARN級別日志* @param args - 日志內容*/static warn(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.WARN);}/*** 打印ERROR級別日志* @param args - 日志內容*/static error(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.ERROR);}/*** 打印FATAL級別日志* @param args - 日志內容*/static fatal(...args: (string | object)[]): void {LogUtil.uniLog(args, hilog.LogLevel.FATAL);}/*** 打印JSON對象或JSON字符串* @param msg - JSON對象或字符串*/static print(msg: object | string): void {try {const content = LogUtil.formatMessage(msg);const len = Math.ceil(content.length / LogUtil.logSize);for (let i = 0; i < len; i++) {const end = Math.min((i + 1) * LogUtil.logSize, content.length);const logMsg = `\n${content.substring(i * LogUtil.logSize, end)}`;LogUtil.levelLog(logMsg, hilog.LogLevel.DEBUG);}} catch (err) {const error = err as BusinessError;console.error(`LogUtil-print-異常 ~ code: ${error.code} -·- message: ${error.message}`);}}/*** 統一日志輸出* @param message - 日志內容* @param level - 日志級別*/private static uniLog(message: (string | object)[], level: hilog.LogLevel): void {if (!LogUtil.showLog) return;const topLine = LogUtil.getLine(LogUtil.tag);LogUtil.levelLog(topLine, level);if (level === hilog.LogLevel.ERROR) {const locationLog = LogUtil.getLogLocation();LogUtil.levelLog(locationLog, level);}const content = LogUtil.formatMessage(message);const len = Math.ceil(content.length / LogUtil.logSize);for (let i = 0; i < len; i++) {const end = Math.min((i + 1) * LogUtil.logSize, content.length);const logMsg = `\n|  ${content.substring(i * LogUtil.logSize, end)}`;LogUtil.levelLog(logMsg, level);}const bottomLine = LogUtil.getLine('');LogUtil.levelLog(bottomLine, level);}/*** 格式化日志內容* @param message - 日志內容,可以是字符串、對象或數組*/private static formatMessage(message: (string | object)[] | object | string): string {let logMessage = '';// Handle array inputif (Array.isArray(message)) {message.forEach((msg: string | object) => {logMessage += typeof msg === 'object' ? LogUtil.getObjectToJson(msg) : String(msg);});}// Handle object inputelse if (typeof message === 'object') {logMessage = LogUtil.getObjectToJson(message);}// Handle string inputelse {logMessage = String(message);}return logMessage;}/*** 對象轉JSON字符串* @param obj - 對象* @param line - 是否格式化換行*/private static getObjectToJson(obj: object, line: boolean = true): string {try {let jsonStr = JSON.stringify(obj, null, 2);if (line) {jsonStr = jsonStr.replace(/\n/g, '\n|\t');jsonStr = jsonStr.replace(/..$/, '  ');}return jsonStr;} catch {return '';}}/*** 獲取代碼位置*/private static getLogLocation(): string {const stackArray = new Error().stack?.split('\n').filter(item => item.trim() !== '').splice(-2) ?? [];const errorLocation = stackArray.join('\n').replace(/\s+/g, '');return `\n|  ${errorLocation}`;}/*** 獲取生成的日志邊框* @param tag - 日志標簽* @param length - 邊框長度*/private static getLine(tag: string = '', length: number = 160): string {if (StrUtil.isNotEmpty(tag)) {return `┌${StrUtil.repeat('─', 10)} ${tag} ${StrUtil.repeat('─', length - tag.length - 2)}`;}return `└${StrUtil.repeat('─', 10)}${StrUtil.repeat('─', length)}`;}/*** 日志打印* @param msg - 日志內容* @param level - 日志級別*/private static levelLog(msg: string, level: hilog.LogLevel): void {if (LogUtil.isHilog) {// Explicitly call the appropriate hilog method based on the log levelswitch (level) {case hilog.LogLevel.DEBUG:hilog.debug(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.INFO:hilog.info(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.WARN:hilog.warn(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.ERROR:hilog.error(LogUtil.domain, LogUtil.tag, msg);break;case hilog.LogLevel.FATAL:hilog.fatal(LogUtil.domain, LogUtil.tag, msg);break;default:console.error(`Unsupported log level: ${level}`);break;}} else {// Fallback to console logging if hilog is not enabledswitch (level) {case hilog.LogLevel.DEBUG:console.debug(msg);break;case hilog.LogLevel.INFO:console.info(msg);break;case hilog.LogLevel.WARN:console.warn(msg);break;case hilog.LogLevel.ERROR:console.error(msg);break;case hilog.LogLevel.FATAL:console.log(msg);break;default:console.error(`Unsupported log level: ${level}`);break;}}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/74186.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/74186.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/74186.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

《Linux運維總結:基于銀河麒麟V10+ARM64架構CPU源碼編譯部署單實例redis7.2.6》

總結&#xff1a;整理不易&#xff0c;如果對你有幫助&#xff0c;可否點贊關注一下&#xff1f; 更多詳細內容請參考&#xff1a;《Linux運維篇&#xff1a;Linux系統運維指南》 一、環境信息 環境信息如下&#xff1a; 主機IP 操作系統 Redis版本 CPU架構 192.168.1.111 K…

基于LSTM的文本分類1——模型搭建

源碼 # coding: UTF-8 import torch import torch.nn as nn import torch.nn.functional as F import numpy as npclass Config(object):"""配置參數類&#xff0c;用于存儲模型和訓練的超參數"""def __init__(self, dataset, embedding):self.…

小了 60,500 倍,但更強;AI 的“深度詛咒”

作者&#xff1a;Ignacio de Gregorio 圖片來自 Unsplash 的 Bahnijit Barman 幾周前&#xff0c;我們看到 Anthropic 嘗試訓練 Claude 去通關寶可夢。模型是有點進展&#xff0c;但離真正通關還差得遠。 但現在&#xff0c;一個獨立的小團隊用一個只有一千萬參數的模型通關了…

nextjs使用02

并行路由 同一個頁面&#xff0c;放多個路由&#xff0c;&#xff0c; 目錄前面加,layout中可以當作插槽引入 import React from "react";function layout({children,notifications,user}:{children:React.ReactNode,notifications:React.ReactNode,user:React.Re…

github 無法在shell里鏈接

當我在shell端git push時&#xff0c;我發現總是22 timeout的問題。 我就進行了以下步驟的嘗試并最終得到了解決。 第一步&#xff0c;我先確定我可以curl github&#xff0c;也就是我網絡沒問題 curl -v https://github.com 如果這個時候不超時和報錯&#xff0c;說明網絡…

當前主流的大模型知識庫軟件對比分析

以下是當前主流的大模型知識庫軟件對比分析&#xff0c;涵蓋功能特性、適用場景及優劣勢&#xff0c;結合最新技術動態和行業實踐提供深度選型參考&#xff1a; 一、企業級智能知識庫平臺 1. 阿里云百煉&#xff08;Model Studio&#xff09; 核心能力&#xff1a;基于RAG技…

Java的比較器 Comparable 和 Comparator

在 Java 中&#xff0c;Comparable 和 Comparator 是用于對象排序的重要接口。它們提供了不同的排序方式&#xff0c;適用于不同的需求&#xff0c;同時在 Java 底層排序算法中發揮著關鍵作用。本文將從基礎概念、使用方法、排序實現&#xff08;包括升序、降序&#xff09;、底…

基于Qlearning強化學習的太赫茲信道信號檢測與識別matlab仿真

目錄 1.算法仿真效果 2.算法涉及理論知識概要 2.1 太赫茲信道特性 2.2 Q-learning強化學習基礎 2.3 基于Q-learning 的太赫茲信道信號檢測與識別系統 3.MATLAB核心程序 4.完整算法代碼文件獲得 1.算法仿真效果 matlab2024b仿真結果如下&#xff08;完整代碼運行后無水印…

力扣刷題————199.二叉樹的右視圖

給定一個二叉樹的 根節點 root&#xff0c;想象自己站在它的右側&#xff0c;按照從頂部到底部的順序&#xff0c;返回從右側所能看到的節點值。 示例 1&#xff1a; 輸入&#xff1a;root [1,2,3,null,5,null,4] 輸出&#xff1a;[1,3,4] 解題思路&#xff1a;我們可以想到這…

文件包含漏洞的小點總結

文件本地與遠程包含&#xff1a; 文件包含有本地包含與遠程包含的區別&#xff1a;本地包含只能包含服務器已經有的問題&#xff1b; 遠程包含可以包含一切網絡上的文件。 本地包含&#xff1a; ①無限制 感受一下使用phpstudy的文件上傳&#xff0c;開啟phpstudy的apache…

深度學習處理時間序列(5)

Keras中的循環層 上面的NumPy簡單實現對應一個實際的Keras層—SimpleRNN層。不過&#xff0c;二者有一點小區別&#xff1a;SimpleRNN層能夠像其他Keras層一樣處理序列批量&#xff0c;而不是像NumPy示例中的那樣只能處理單個序列。也就是說&#xff0c;它接收形狀為(batch_si…

操作系統相關知識點

操作系統在進行線程切換時需要進行哪些動作&#xff1f; 保存當前線程的上下文 保存寄存器狀態、保存棧信息。 調度器選擇下一個線程 調度算法決策&#xff1a;根據策略&#xff08;如輪轉、優先級、公平共享&#xff09;從就緒隊列選擇目標線程。 處理優先級&#xff1a;實時…

從0到1:Rust 如何用 FFmpeg 和 OpenGL 打造硬核視頻特效

引言&#xff1a;視頻特效開發的痛點&#xff0c;你中了幾個&#xff1f; 視頻特效如今無處不在&#xff1a;短視頻平臺的濾鏡美化、直播間的實時美顏、影視后期的電影級調色&#xff0c;甚至 AI 生成內容的動態效果。無論是個人開發者還是團隊&#xff0c;視頻特效都成了吸引…

【并發編程 | 第一篇】線程相關基礎知識

1.并發和并行有什么區別 并發是指多核CPU上的多任務處理&#xff0c;多個任務在同一時刻真正同時執行。 并行是指單核CPU上的多任務處理&#xff0c;多個任務在同一時間段內交替執行&#xff0c;通過時間片輪轉實現交替執行&#xff0c;用于解決IO密集型瓶頸。 如何理解線程安…

Kafka 偏移量

在 Apache Kafka 中&#xff0c;偏移量&#xff08;Offset&#xff09;是一個非常重要的概念。它不僅用于標識消息的位置&#xff0c;還在多種場景中發揮關鍵作用。本文將詳細介紹 Kafka 偏移量的核心概念及其使用場景。 一、偏移量的核心概念 1. 定義 偏移量是一個非負整數…

18.redis基本操作

Redis(Remote Dictionary Server)是一個開源的、高性能的鍵值對(Key-Value)存儲數據庫,廣泛應用于緩存、消息隊列、實時分析等場景。它以其極高的讀寫速度、豐富的數據結構和靈活的應用方式而受到開發者的青睞。 Redis 的主要特點 ?高性能: ?內存存儲:Redis 將所有數…

歷年跨鏈合約惡意交易詳解(一)——THORChain退款邏輯漏洞

漏洞合約函數 function returnVaultAssets(address router, address payable asgard, Coin[] memory coins, string memory memo) public payable {if (router address(this)){for(uint i 0; i < coins.length; i){_adjustAllowances(asgard, coins[i].asset, coins[i].a…

通俗易懂的講解SpringBean生命周期

&#x1f4d5;我是廖志偉&#xff0c;一名Java開發工程師、《Java項目實戰——深入理解大型互聯網企業通用技術》&#xff08;基礎篇&#xff09;、&#xff08;進階篇&#xff09;、&#xff08;架構篇&#xff09;清華大學出版社簽約作家、Java領域優質創作者、CSDN博客專家、…

深入理解 `git pull --rebase` 與 `--allow-unrelated-histories`:區別、原理與實戰指南

&#x1f680; git pull --rebase vs --allow-unrelated-histories 全面解析 在日常使用 Git 時&#xff0c;我們經常遇到兩種拉取遠程代碼的方式&#xff1a;git pull --rebase 和 git pull --allow-unrelated-histories。它們的區別是什么&#xff1f;各自適用哪些場景&…

Matlab_Simulink中導入CSV數據與仿真實現方法

前言 在Simulink仿真中&#xff0c;常需將外部數據&#xff08;如CSV文件或MATLAB工作空間變量&#xff09;作為輸入信號驅動模型。本文介紹如何高效導入CSV數據至MATLAB工作空間&#xff0c;并通過From Workspace模塊實現數據到Simulink的精確傳輸&#xff0c;適用于運動控制…