feat: add log function

This commit is contained in:
Gabe Yuan
2024-03-19 18:07:18 +08:00
parent 1d9e9c1b7d
commit 6e927473b9
24 changed files with 76 additions and 41 deletions

View File

@@ -3,6 +3,7 @@ import { useCallback, useEffect, useState } from "react";
import { trySyncWords } from "../libs/sync"; import { trySyncWords } from "../libs/sync";
import { getWordsWithDefault, setWords } from "../libs/storage"; import { getWordsWithDefault, setWords } from "../libs/storage";
import { useSyncMeta } from "./Sync"; import { useSyncMeta } from "./Sync";
import { kissLog } from "../libs/log";
export function useFavWords() { export function useFavWords() {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -56,7 +57,7 @@ export function useFavWords() {
const favWords = await getWordsWithDefault(); const favWords = await getWordsWithDefault();
setFavWords(favWords); setFavWords(favWords);
} catch (err) { } catch (err) {
console.log("[query fav]", err); kissLog(err, "query fav");
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -1,11 +1,12 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { storage } from "../libs/storage"; import { storage } from "../libs/storage";
import { kissLog } from "../libs/log";
/** /**
* *
* @param {*} key * @param {*} key
* @param {*} defaultVal 需为调用hook外的常量 * @param {*} defaultVal 需为调用hook外的常量
* @returns * @returns
*/ */
export function useStorage(key, defaultVal) { export function useStorage(key, defaultVal) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -40,7 +41,7 @@ export function useStorage(key, defaultVal) {
setData(val); setData(val);
} }
} catch (err) { } catch (err) {
console.log("[storage reload]", err.message); kissLog(err, "storage reload");
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -58,7 +59,7 @@ export function useStorage(key, defaultVal) {
await storage.setObj(key, defaultVal); await storage.setObj(key, defaultVal);
} }
} catch (err) { } catch (err) {
console.log("[storage load]", err.message); kissLog(err, "storage load");
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -3,6 +3,7 @@ import { useSetting } from "./Setting";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { loadOrFetchSubRules } from "../libs/subRules"; import { loadOrFetchSubRules } from "../libs/subRules";
import { delSubRules } from "../libs/storage"; import { delSubRules } from "../libs/storage";
import { kissLog } from "../libs/log";
/** /**
* 订阅规则 * 订阅规则
@@ -72,7 +73,7 @@ export function useSubRules() {
const rules = await loadOrFetchSubRules(selectedUrl); const rules = await loadOrFetchSubRules(selectedUrl);
setSelectedRules(rules); setSelectedRules(rules);
} catch (err) { } catch (err) {
console.log("[loadOrFetchSubRules]", err); kissLog(err, "loadOrFetchSubRules");
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -3,6 +3,7 @@ import { useState } from "react";
import { tryDetectLang } from "../libs"; import { tryDetectLang } from "../libs";
import { apiTranslate } from "../apis"; import { apiTranslate } from "../apis";
import { DEFAULT_TRANS_APIS } from "../config"; import { DEFAULT_TRANS_APIS } from "../config";
import { kissLog } from "../libs/log";
/** /**
* 翻译hook * 翻译hook
@@ -45,7 +46,7 @@ export function useTranslate(q, rule, setting) {
setSamelang(isSame); setSamelang(isSame);
} }
} catch (err) { } catch (err) {
console.log("[translate]", err); kissLog(err, "translate");
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -1,12 +1,13 @@
import { getMsauth, setMsauth } from "./storage"; import { getMsauth, setMsauth } from "./storage";
import { URL_MICROSOFT_AUTH } from "../config"; import { URL_MICROSOFT_AUTH } from "../config";
import { fetchData } from "./fetch"; import { fetchData } from "./fetch";
import { kissLog } from "./log";
const parseMSToken = (token) => { const parseMSToken = (token) => {
try { try {
return JSON.parse(atob(token.split(".")[1])).exp; return JSON.parse(atob(token.split(".")[1])).exp;
} catch (err) { } catch (err) {
console.log("[parseMSToken]", err); kissLog(err, "parseMSToken");
} }
return 0; return 0;
}; };

View File

@@ -8,7 +8,7 @@ function _browser() {
try { try {
return require("webextension-polyfill"); return require("webextension-polyfill");
} catch (err) { } catch (err) {
// console.log("[browser]", err.message); // kissLog(err, "browser");
} }
} }

View File

@@ -11,6 +11,7 @@ import {
} from "../config"; } from "../config";
import { isBg } from "./browser"; import { isBg } from "./browser";
import { newCacheReq, newTransReq } from "./req"; import { newCacheReq, newTransReq } from "./req";
import { kissLog } from "./log";
const TIMEOUT = 5000; const TIMEOUT = 5000;
@@ -125,7 +126,7 @@ export const fetchData = async (
const cache = await caches.open(CACHE_NAME); const cache = await caches.open(CACHE_NAME);
res = await cache.match(cacheReq); res = await cache.match(cacheReq);
} catch (err) { } catch (err) {
console.log("[cache match]", err.message); kissLog(err, "cache match");
} }
} }
@@ -154,7 +155,7 @@ export const fetchData = async (
const cache = await caches.open(CACHE_NAME); const cache = await caches.open(CACHE_NAME);
await cache.put(cacheReq, res.clone()); await cache.put(cacheReq, res.clone());
} catch (err) { } catch (err) {
console.log("[cache put]", err.message); kissLog(err, "cache put");
} }
} }
} }

View File

@@ -1,6 +1,7 @@
import { CACHE_NAME } from "../config"; import { CACHE_NAME } from "../config";
import { browser } from "./browser"; import { browser } from "./browser";
import { apiBaiduLangdetect } from "../apis"; import { apiBaiduLangdetect } from "../apis";
import { kissLog } from "./log";
/** /**
* 清除缓存数据 * 清除缓存数据
@@ -9,7 +10,7 @@ export const tryClearCaches = async () => {
try { try {
caches.delete(CACHE_NAME); caches.delete(CACHE_NAME);
} catch (err) { } catch (err) {
console.log("[clean caches]", err.message); kissLog(err, "clean caches");
} }
}; };
@@ -25,7 +26,7 @@ export const tryDetectLang = async (q, useRemote = false) => {
try { try {
lang = await apiBaiduLangdetect(q); lang = await apiBaiduLangdetect(q);
} catch (err) { } catch (err) {
console.log("[detect lang remote]", err.message); kissLog(err, "detect lang remote");
} }
} }
@@ -34,7 +35,7 @@ export const tryDetectLang = async (q, useRemote = false) => {
const res = await browser?.i18n?.detectLanguage(q); const res = await browser?.i18n?.detectLanguage(q);
lang = res?.languages?.[0]?.language; lang = res?.languages?.[0]?.language;
} catch (err) { } catch (err) {
console.log("[detect lang local]", err.message); kissLog(err, "detect lang local");
} }
} }

View File

@@ -8,6 +8,7 @@ import { genEventName, removeEndchar, matchInputStr, sleep } from "./utils";
import { stepShortcutRegister } from "./shortcut"; import { stepShortcutRegister } from "./shortcut";
import { apiTranslate } from "../apis"; import { apiTranslate } from "../apis";
import { loadingSvg } from "./svg"; import { loadingSvg } from "./svg";
import { kissLog } from "./log";
function isInputNode(node) { function isInputNode(node) {
return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA"; return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA";
@@ -187,7 +188,7 @@ export default function inputTranslate({
collapseToEnd(node); collapseToEnd(node);
} }
} catch (err) { } catch (err) {
console.log("[translate input]", err.message); kissLog(err, "translate input");
} finally { } finally {
removeLoading(node, loadingId); removeLoading(node, loadingId);
} }

12
src/libs/log.js Normal file
View File

@@ -0,0 +1,12 @@
/**
* 日志函数
* @param {*} msg
* @param {*} type
*/
export const kissLog = (msg, type) => {
let prefix = `[KISS-Translator]`;
if (type) {
prefix += `[${type}]`;
}
console.log(`${prefix} ${msg}`);
};

View File

@@ -1,3 +1,5 @@
import { kissLog } from "./log";
/** /**
* 任务池 * 任务池
* @param {*} fn * @param {*} fn
@@ -35,7 +37,7 @@ export const taskPool = (
const res = await fn({ ...args, ...preArgs }); const res = await fn({ ...args, ...preArgs });
resolve(res); resolve(res);
} catch (err) { } catch (err) {
console.log("[task]", retry, err); kissLog(err, "task");
if (retry < maxRetry) { if (retry < maxRetry) {
const retryTimer = setTimeout(() => { const retryTimer = setTimeout(() => {
clearTimeout(retryTimer); clearTimeout(retryTimer);

View File

@@ -13,6 +13,7 @@ import { loadOrFetchSubRules } from "./subRules";
import { getRulesWithDefault, setRules } from "./storage"; import { getRulesWithDefault, setRules } from "./storage";
import { trySyncRules } from "./sync"; import { trySyncRules } from "./sync";
import { FIXER_ALL } from "./webfix"; import { FIXER_ALL } from "./webfix";
import { kissLog } from "./log";
/** /**
* 根据href匹配规则 * 根据href匹配规则
@@ -49,7 +50,7 @@ export const matchRule = async (
rules.splice(-1, 0, ...subRules); rules.splice(-1, 0, ...subRules);
} }
} catch (err) { } catch (err) {
console.log("[load injectRules]", err); kissLog(err, "load injectRules");
} }
} }

View File

@@ -14,6 +14,7 @@ import {
} from "../config"; } from "../config";
import { isExt, isGm } from "./client"; import { isExt, isGm } from "./client";
import { browser } from "./browser"; import { browser } from "./browser";
import { kissLog } from "./log";
async function set(key, val) { async function set(key, val) {
if (isExt) { if (isExt) {
@@ -155,6 +156,6 @@ export const tryInitDefaultData = async () => {
BUILTIN_RULES BUILTIN_RULES
); );
} catch (err) { } catch (err) {
console.log("[init default]", err); kissLog(err, "init default");
} }
}; };

View File

@@ -8,6 +8,7 @@ import {
import { apiFetch } from "../apis"; import { apiFetch } from "../apis";
import { checkRules } from "./rules"; import { checkRules } from "./rules";
import { isAllchar } from "./utils"; import { isAllchar } from "./utils";
import { kissLog } from "./log";
/** /**
* 更新缓存同步时间 * 更新缓存同步时间
@@ -46,7 +47,7 @@ export const syncAllSubRules = async (subrulesList) => {
await syncSubRules(subrules.url); await syncSubRules(subrules.url);
await updateSyncDataCache(subrules.url); await updateSyncDataCache(subrules.url);
} catch (err) { } catch (err) {
console.log(`[sync subrule error]: ${subrules.url}`, err); kissLog(err, `sync subrule error: ${subrules.url}`);
} }
} }
}; };
@@ -67,7 +68,7 @@ export const trySyncAllSubRules = async ({ subrulesList }) => {
await updateSync({ subRulesSyncAt: now }); await updateSync({ subRulesSyncAt: now });
} }
} catch (err) { } catch (err) {
console.log("[try sync all subrules]", err); kissLog(err, "try sync all subrules");
} }
}; };

View File

@@ -21,6 +21,7 @@ import { apiSyncData } from "../apis";
import { sha256, removeEndchar } from "./utils"; import { sha256, removeEndchar } from "./utils";
import { createClient, getPatcher } from "webdav"; import { createClient, getPatcher } from "webdav";
import { fetchApi } from "./fetch"; import { fetchApi } from "./fetch";
import { kissLog } from "./log";
getPatcher().patch("request", (opts) => { getPatcher().patch("request", (opts) => {
return fetchApi({ return fetchApi({
@@ -115,7 +116,7 @@ export const trySyncSetting = async () => {
try { try {
await syncSetting(); await syncSetting();
} catch (err) { } catch (err) {
console.log("[sync setting]", err); kissLog(err, "sync setting");
} }
}; };
@@ -134,7 +135,7 @@ export const trySyncRules = async () => {
try { try {
await syncRules(); await syncRules();
} catch (err) { } catch (err) {
console.log("[sync user rules]", err); kissLog(err, "sync user rules");
} }
}; };
@@ -153,7 +154,7 @@ export const trySyncWords = async () => {
try { try {
await syncWords(); await syncWords();
} catch (err) { } catch (err) {
console.log("[sync fav words]", err); kissLog(err, "sync fav words");
} }
}; };

View File

@@ -22,6 +22,7 @@ import { apiTranslate } from "../apis";
import { sendBgMsg } from "./msg"; import { sendBgMsg } from "./msg";
import { isExt } from "./client"; import { isExt } from "./client";
import { injectInlineJs, injectInternalCss } from "./injector"; import { injectInlineJs, injectInternalCss } from "./injector";
import { kissLog } from "./log";
/** /**
* 翻译类 * 翻译类
@@ -193,7 +194,7 @@ export class Translator {
try { try {
return Array.from(node.querySelectorAll(selector)); return Array.from(node.querySelectorAll(selector));
} catch (err) { } catch (err) {
console.log(`[querySelectorAll err]: ${selector}`); kissLog(selector, "querySelectorAll err");
} }
return []; return [];
}; };

View File

@@ -21,6 +21,7 @@ import {
} from "../../config"; } from "../../config";
import { shortcutRegister } from "../../libs/shortcut"; import { shortcutRegister } from "../../libs/shortcut";
import { sendIframeMsg } from "../../libs/iframe"; import { sendIframeMsg } from "../../libs/iframe";
import { kissLog } from "../../libs/log";
export default function Action({ translator, fab }) { export default function Action({ translator, fab }) {
const fabWidth = 40; const fabWidth = 40;
@@ -138,7 +139,7 @@ export default function Action({ translator, fab }) {
}); });
}; };
} catch (err) { } catch (err) {
console.log("[registerMenuCommand]", err); kissLog(err, "registerMenuCommand");
} }
}, [translator]); }, [translator]);

View File

@@ -18,6 +18,7 @@ import UploadButton from "./UploadButton";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import ClearAllIcon from "@mui/icons-material/ClearAll"; import ClearAllIcon from "@mui/icons-material/ClearAll";
import { isValidWord } from "../../libs/utils"; import { isValidWord } from "../../libs/utils";
import { kissLog } from "../../libs/log";
function DictField({ word }) { function DictField({ word }) {
const [dictResult, setDictResult] = useState(null); const [dictResult, setDictResult] = useState(null);
@@ -93,7 +94,7 @@ export default function FavWords() {
.filter(isValidWord); .filter(isValidWord);
await mergeWords(newWords); await mergeWords(newWords);
} catch (err) { } catch (err) {
console.log("[import rules]", err); kissLog(err, "import rules");
} }
}; };

View File

@@ -59,6 +59,7 @@ import AddIcon from "@mui/icons-material/Add";
import EditIcon from "@mui/icons-material/Edit"; import EditIcon from "@mui/icons-material/Edit";
import CancelIcon from "@mui/icons-material/Cancel"; import CancelIcon from "@mui/icons-material/Cancel";
import SaveIcon from "@mui/icons-material/Save"; import SaveIcon from "@mui/icons-material/Save";
import { kissLog } from "../../libs/log";
function RuleFields({ rule, rules, setShow, setKeyword }) { function RuleFields({ rule, rules, setShow, setKeyword }) {
const initFormValues = { const initFormValues = {
@@ -701,7 +702,7 @@ function ShareButton({ rules, injectRules, selectedUrl }) {
window.open(url, "_blank"); window.open(url, "_blank");
} catch (err) { } catch (err) {
alert.warning(i18n("error_got_some_wrong")); alert.warning(i18n("error_got_some_wrong"));
console.log("[share rules]", err); kissLog(err, "share rules");
} }
}; };
@@ -731,7 +732,7 @@ function UserRules({ subRules }) {
try { try {
await rules.merge(JSON.parse(data)); await rules.merge(JSON.parse(data));
} catch (err) { } catch (err) {
console.log("[import rules]", err); kissLog(err, "import rules");
} }
}; };
@@ -864,7 +865,7 @@ function SubRulesItem({
await delSubRules(url); await delSubRules(url);
await deleteDataCache(url); await deleteDataCache(url);
} catch (err) { } catch (err) {
console.log("[del subrules]", err); kissLog(err, "del subrules");
} }
}; };
@@ -877,7 +878,7 @@ function SubRulesItem({
} }
await updateDataCache(url); await updateDataCache(url);
} catch (err) { } catch (err) {
console.log("[sync sub rules]", err); kissLog(err, "sync sub rules");
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -956,7 +957,7 @@ function SubRulesEdit({ subList, addSub, updateDataCache }) {
setShowInput(false); setShowInput(false);
setInputText(""); setInputText("");
} catch (err) { } catch (err) {
console.log("[fetch rules]", err); kissLog(err, "fetch rules");
setInputError(i18n("error_fetch_url")); setInputError(i18n("error_fetch_url"));
} finally { } finally {
setLoading(false); setLoading(false);

View File

@@ -28,6 +28,7 @@ import { useShortcut } from "../../hooks/Shortcut";
import ShortcutInput from "./ShortcutInput"; import ShortcutInput from "./ShortcutInput";
import { useFab } from "../../hooks/Fab"; import { useFab } from "../../hooks/Fab";
import { sendBgMsg } from "../../libs/msg"; import { sendBgMsg } from "../../libs/msg";
import { kissLog } from "../../libs/log";
function ShortcutItem({ action, label }) { function ShortcutItem({ action, label }) {
const { shortcut, setShortcut } = useShortcut(action); const { shortcut, setShortcut } = useShortcut(action);
@@ -82,7 +83,7 @@ export default function Settings() {
caches.delete(CACHE_NAME); caches.delete(CACHE_NAME);
alert.success(i18n("clear_success")); alert.success(i18n("clear_success"));
} catch (err) { } catch (err) {
console.log("[clear cache]", err); kissLog(err, "clear cache");
} }
}; };

View File

@@ -19,6 +19,7 @@ import { useAlert } from "../../hooks/Alert";
import SyncIcon from "@mui/icons-material/Sync"; import SyncIcon from "@mui/icons-material/Sync";
import CircularProgress from "@mui/material/CircularProgress"; import CircularProgress from "@mui/material/CircularProgress";
import { useSetting } from "../../hooks/Setting"; import { useSetting } from "../../hooks/Setting";
import { kissLog } from "../../libs/log";
export default function SyncSetting() { export default function SyncSetting() {
const i18n = useI18n(); const i18n = useI18n();
@@ -43,7 +44,7 @@ export default function SyncSetting() {
await reloadSetting(); await reloadSetting();
alert.success(i18n("sync_success")); alert.success(i18n("sync_success"));
} catch (err) { } catch (err) {
console.log("[sync all]", err); kissLog(err, "sync all");
alert.error(i18n("sync_failed")); alert.error(i18n("sync_failed"));
} finally { } finally {
setLoading(false); setLoading(false);

View File

@@ -27,6 +27,7 @@ import {
import { sendIframeMsg } from "../../libs/iframe"; import { sendIframeMsg } from "../../libs/iframe";
import { saveRule } from "../../libs/rules"; import { saveRule } from "../../libs/rules";
import { tryClearCaches } from "../../libs"; import { tryClearCaches } from "../../libs";
import { kissLog } from "../../libs/log";
export default function Popup({ setShowPopup, translator: tran }) { export default function Popup({ setShowPopup, translator: tran }) {
const i18n = useI18n(); const i18n = useI18n();
@@ -55,7 +56,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
sendIframeMsg(MSG_TRANS_TOGGLE); sendIframeMsg(MSG_TRANS_TOGGLE);
} }
} catch (err) { } catch (err) {
console.log("[toggle trans]", err); kissLog(err, "toggle trans");
} }
}; };
@@ -71,7 +72,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
sendIframeMsg(MSG_TRANS_PUTRULE, { [name]: value }); sendIframeMsg(MSG_TRANS_PUTRULE, { [name]: value });
} }
} catch (err) { } catch (err) {
console.log("[update rule]", err); kissLog(err, "update rule");
} }
}; };
@@ -93,7 +94,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
saveRule(newRule); saveRule(newRule);
} }
} catch (err) { } catch (err) {
console.log("[save rule]", err); kissLog(err, "save rule");
} }
}; };
@@ -108,7 +109,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
setRule(res.data); setRule(res.data);
} }
} catch (err) { } catch (err) {
console.log("[query rule]", err); kissLog(err, "query rule");
} }
})(); })();
}, [tran]); }, [tran]);
@@ -132,7 +133,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
} }
setCommands(commands); setCommands(commands);
} catch (err) { } catch (err) {
console.log("[query cmds]", err); kissLog(err, "query cmds");
} }
})(); })();
}, [tran]); }, [tran]);

View File

@@ -3,6 +3,7 @@ import FavoriteIcon from "@mui/icons-material/Favorite";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder"; import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import { useState } from "react"; import { useState } from "react";
import { useFavWords } from "../../hooks/FavWords"; import { useFavWords } from "../../hooks/FavWords";
import { kissLog } from "../../libs/log";
export default function FavBtn({ word }) { export default function FavBtn({ word }) {
const { favWords, toggleFav } = useFavWords(); const { favWords, toggleFav } = useFavWords();
@@ -13,7 +14,7 @@ export default function FavBtn({ word }) {
setLoading(true); setLoading(true);
await toggleFav(word); await toggleFav(word);
} catch (err) { } catch (err) {
console.log("[set fav]", err); kissLog(err, "set fav");
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -6,6 +6,7 @@ import { sleep, limitNumber } from "../../libs/utils";
import { isGm, isExt } from "../../libs/client"; import { isGm, isExt } from "../../libs/client";
import { MSG_OPEN_TRANBOX, DEFAULT_TRANBOX_SHORTCUT } from "../../config"; import { MSG_OPEN_TRANBOX, DEFAULT_TRANBOX_SHORTCUT } from "../../config";
import { isMobile } from "../../libs/mobile"; import { isMobile } from "../../libs/mobile";
import { kissLog } from "../../libs/log";
export default function Slection({ export default function Slection({
contextMenuType, contextMenuType,
@@ -127,7 +128,7 @@ export default function Slection({
}); });
}; };
} catch (err) { } catch (err) {
console.log("[registerMenuCommand]", err); kissLog(err, "registerMenuCommand");
} }
}, [handleTranbox, contextMenuType]); }, [handleTranbox, contextMenuType]);