feat: 支持查看日志(前端>=2.16.60)

This commit is contained in:
xream committed 2026-04-24 16:58:49 +08:00
1 parent ea8bb4d642
commit 89767ce2ab
15 files changed
+860 -20

No files matched your search

+4 -1
View File
@@ -138,4 +138,7 @@ backend/sub-store.min.js
CHANGELOG.md
.codeartsdoer
.github/copilot-instructions.md
.github/copilot-instructions.md
CODEMAP.md
CONTEXT_BUNDLE.md
mydocs
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.22.6",
"version": "2.22.7",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"scripts": {
+2
View File
@@ -14,6 +14,8 @@ export const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository';
export const RESOURCE_CACHE_KEY = '#sub-store-cached-resource';
export const HEADERS_RESOURCE_CACHE_KEY = '#sub-store-cached-headers-resource';
export const SCRIPT_RESOURCE_CACHE_KEY = '#sub-store-cached-script-resource';
export const LOGS_KEY = '#sub-store-logs';
export const DEFAULT_CACHE_TTL = 60 * 60 * 1000; // 1 hour
export const DEFAULT_HEADERS_CACHE_TTL = 60 * 1000; // 1 min
export const DEFAULT_SCRIPT_CACHE_TTL = 48 * 3600 * 1000; // 48 hours
export const DEFAULT_LOGS_MAX_COUNT = 0;
+1 -5
View File
@@ -373,11 +373,7 @@ function produce(proxies, targetPlatform, type, opts = {}) {
return producer.produce(proxy, type, opts);
} catch (err) {
$.error(
`Cannot produce proxy: ${JSON.stringify(
proxy,
null,
2,
)}\nReason: ${err}`,
`Cannot produce proxy: ${proxy.name}\nReason: ${err}`,
);
return '';
}
@@ -580,11 +580,7 @@ export default function Egern_Producer() {
};
} catch (err) {
$.error(
`Cannot produce proxy: ${JSON.stringify(
sourceProxy,
null,
2,
)}\nReason: ${err}`,
`Cannot produce proxy: ${proxy.name}\nReason: ${err}`,
);
return null;
}
@@ -13,13 +13,7 @@ export default function V2Ray_Producer() {
try {
result.push(URI.produce(proxy));
} catch (err) {
$.error(
`Cannot produce proxy: ${JSON.stringify(
proxy,
null,
2,
)}\nReason: ${err}`,
);
$.error(`Cannot produce proxy: ${proxy.name}\nReason: ${err}`);
}
});
+2
View File
@@ -24,6 +24,7 @@ import registerFileRoutes from '@/restful/file';
import registerTokenRoutes from '@/restful/token';
import registerArchiveRoutes from '@/restful/archives';
import registerModuleRoutes from '@/restful/module';
import registerLogRoutes from '@/restful/logs';
migrate();
serve();
@@ -42,6 +43,7 @@ function serve() {
registerSortRoutes($app);
registerArchiveRoutes($app);
registerMiscRoutes($app);
registerLogRoutes($app);
$app.start();
}
+2
View File
@@ -23,6 +23,7 @@ import registerSortingRoutes from './sort';
import registerMiscRoutes from './miscs';
import registerNodeInfoRoutes from './node-info';
import registerParserRoutes from './parser';
import registerLogRoutes from './logs';
export default function serve() {
let port;
@@ -139,6 +140,7 @@ export default function serve() {
registerNodeInfoRoutes($app);
registerMiscRoutes($app);
registerParserRoutes($app);
registerLogRoutes($app);
$app.start();
+52
View File
@@ -0,0 +1,52 @@
import $ from '@/core/app';
import { InternalServerError, RequestInvalidError } from '@/restful/errors';
import { failed, success } from '@/restful/response';
import { clearLogEntries, getLogEntries } from '@/utils/debug-logs';
export default function register($app) {
$app.route('/api/logs').get(getLogs).delete(clearLogs);
}
function getLogs(req, res) {
try {
success(res, getLogEntries($, req.query || {}));
} catch (e) {
if (e instanceof SyntaxError) {
failed(
res,
new RequestInvalidError(
'INVALID_LOG_KEYWORD_REGEX',
'Invalid log keyword regular expression',
`Reason: ${e.message ?? e}`,
),
400,
);
return;
}
failed(
res,
new InternalServerError(
'FAILED_TO_GET_LOGS',
'Failed to get logs',
`Reason: ${e.message ?? e}`,
),
);
}
}
function clearLogs(req, res) {
try {
clearLogEntries($);
success(res);
} catch (e) {
failed(
res,
new InternalServerError(
'FAILED_TO_CLEAR_LOGS',
'Failed to clear logs',
`Reason: ${e.message ?? e}`,
),
);
}
}
+15
View File
@@ -3,6 +3,7 @@ import { success, failed } from './response';
import { InternalServerError } from '@/restful/errors';
import $ from '@/core/app';
import Gist from '@/utils/gist';
import { clearLogSettingsCache } from '@/utils/debug-logs';
export default function register($app) {
const settings = $.read(SETTINGS_KEY);
@@ -54,7 +55,21 @@ async function updateSettings(req, res) {
delete newSettings[key];
}
});
if ('logsMaxCount' in newSettings) {
const rawLogsMaxCount = newSettings.logsMaxCount;
const value = Number(rawLogsMaxCount);
if (
rawLogsMaxCount === null ||
rawLogsMaxCount === undefined ||
rawLogsMaxCount === '' ||
!isFinite(value) ||
value < 0
) {
delete newSettings.logsMaxCount;
}
}
$.write(newSettings, SETTINGS_KEY);
clearLogSettingsCache();
if (
req.body.githubUser ||
req.body.gistToken ||
+432
View File
@@ -0,0 +1,432 @@
import { expect } from 'chai';
import { after, before, beforeEach, describe, it } from 'mocha';
import { LOGS_KEY, SETTINGS_KEY } from '@/constants';
let $;
let appendLogEntry;
let getLogEntries;
let clearLogEntries;
let clearLogSettingsCache;
let registerLogRoutes;
let registerSettingsRoutes;
let originalRead;
let originalWrite;
let state;
const SUB_STORE_BANNER = `
${'\u2505'.repeat(44)}
Sub-Store -- v2.22.6
${'\u2505'.repeat(44)}
`;
const SUB_STORE_PLATFORM_BANNER = `
${'\u2505'.repeat(44)}
Sub-Store -- v2.22.6
Loon -- Loon(842)
${'\u2505'.repeat(44)}
`;
const DEFAULT_IGNORED_NOISE_LOGS = [
'[sub-store] INFO: Surge AnyTLS Parser is activated',
'[sub-store] ERROR: Fallback Base64 Pre-processor error: decoded line does not start with protocol',
];
const DEFAULT_VISIBLE_PREPROCESSOR_LOGS = [
'[sub-store] INFO: Pre-processor [Fallback Base64 Pre-processor] activated',
'[sub-store] INFO: Pre-processor [Clash Pre-processor] activated',
];
function createRouteApp() {
const handlers = new Map();
const methods = ['get', 'delete', 'patch'];
const app = {
handlers,
route(pattern) {
const chain = {};
methods.forEach((method) => {
chain[method] = (handler) => {
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
return chain;
};
});
return chain;
},
};
methods.forEach((method) => {
app[method] = (pattern, handler) => {
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
return app;
};
});
return app;
}
function getHandler(method, pattern) {
const app = createRouteApp();
registerLogRoutes(app);
return app.handlers.get(`${method} ${pattern}`);
}
function createResponse(routePath) {
return {
body: null,
req: {
route: {
path: routePath,
},
},
statusCode: 200,
status(code) {
this.statusCode = code;
return this;
},
json(payload) {
this.body = payload;
return this;
},
};
}
describe('logs routes', function () {
before(async function () {
({ default: $ } = require('@/core/app'));
({
appendLogEntry,
getLogEntries,
clearLogEntries,
clearLogSettingsCache,
} = require('@/utils/debug-logs'));
({ default: registerLogRoutes } = require('@/restful/logs'));
({ default: registerSettingsRoutes } = require('@/restful/settings'));
originalRead = $.read.bind($);
originalWrite = $.write.bind($);
});
after(function () {
if ($) {
$.read = originalRead;
$.write = originalWrite;
}
});
beforeEach(function () {
state = {
[SETTINGS_KEY]: { logsMaxCount: 500 },
[LOGS_KEY]: '[]',
};
$.read = (key) => state[key];
$.write = (data, key) => {
state[key] = data;
return true;
};
clearLogSettingsCache();
});
it('persists log entries and trims by logsMaxCount', function () {
state[SETTINGS_KEY] = { logsMaxCount: 2 };
appendLogEntry($, 'info', ['first']);
appendLogEntry($, 'warn', ['second']);
appendLogEntry($, 'error', ['third']);
const storedLogs = JSON.parse(state[LOGS_KEY]);
expect(storedLogs).to.have.length(2);
expect(storedLogs[0].message).to.equal('[unknown] WARN: second');
expect(storedLogs[1].message).to.equal('[unknown] ERROR: third');
});
it('disables persistent log cache IO when logsMaxCount is zero', function () {
state[SETTINGS_KEY] = { logsMaxCount: 0 };
state[LOGS_KEY] = JSON.stringify([
{
id: 'existing-log',
time: 1,
level: 'info',
message: '[unknown] INFO: existing',
},
]);
const readKeys = [];
const writeKeys = [];
$.read = (key) => {
readKeys.push(key);
return state[key];
};
$.write = (data, key) => {
writeKeys.push(key);
state[key] = data;
return true;
};
appendLogEntry($, 'info', ['disabled write']);
expect(readKeys).to.deep.equal([SETTINGS_KEY]);
expect(writeKeys).to.deep.equal([]);
expect(
JSON.parse(state[LOGS_KEY]).map((log) => log.message),
).to.deep.equal(['[unknown] INFO: existing']);
readKeys.length = 0;
const result = getLogEntries($, { limit: 10 });
expect(result).to.deep.equal({
logs: [],
total: 0,
maxCount: 0,
});
expect(readKeys).to.deep.equal([SETTINGS_KEY]);
expect(writeKeys).to.deep.equal([]);
});
it('disables persistent log cache IO by default', function () {
state[SETTINGS_KEY] = {};
appendLogEntry($, 'info', ['default disabled write']);
expect(JSON.parse(state[LOGS_KEY])).to.deep.equal([]);
expect(getLogEntries($, { limit: 10 })).to.deep.equal({
logs: [],
total: 0,
maxCount: 0,
});
});
it('preserves explicit zero logsMaxCount in settings', async function () {
const app = createRouteApp();
registerSettingsRoutes(app);
const patchHandler = app.handlers.get('PATCH /api/settings');
const zeroRes = createResponse('/api/settings');
await patchHandler({ body: { logsMaxCount: '0' } }, zeroRes);
expect(zeroRes.body.status).to.equal('success');
expect(state[SETTINGS_KEY]).to.deep.include({
logsMaxCount: '0',
});
const emptyRes = createResponse('/api/settings');
await patchHandler({ body: { logsMaxCount: '' } }, emptyRes);
expect(emptyRes.body.status).to.equal('success');
expect(state[SETTINGS_KEY]).to.not.have.property('logsMaxCount');
});
it('normalizes stored log messages with missing scope or level', function () {
appendLogEntry($, 'log', [
'[测试] 有 scope 无 level 的日志: 🇺🇸 Oracle [snell]',
]);
appendLogEntry($, 'warn', [
'测试无 scope 无 level 的日志: 🇺🇸 Oracle [snell]',
]);
appendLogEntry($, 'error', [
'[测试] ERROR: 已经完整的日志: 🇺🇸 Oracle [snell]',
]);
expect(
JSON.parse(state[LOGS_KEY]).map((log) => log.message),
).to.deep.equal([
'[测试] LOG: 有 scope 无 level 的日志: 🇺🇸 Oracle [snell]',
'[unknown] WARN: 测试无 scope 无 level 的日志: 🇺🇸 Oracle [snell]',
'[测试] ERROR: 已经完整的日志: 🇺🇸 Oracle [snell]',
]);
});
it('skips Sub-Store startup banner logs when appending', function () {
appendLogEntry($, 'log', [SUB_STORE_BANNER]);
appendLogEntry($, 'log', [SUB_STORE_PLATFORM_BANNER]);
expect(JSON.parse(state[LOGS_KEY])).to.deep.equal([]);
});
it('skips default noisy parser and fallback preprocessor error logs when appending', function () {
DEFAULT_IGNORED_NOISE_LOGS.forEach((message) => {
appendLogEntry($, 'info', [message]);
});
appendLogEntry($, 'info', ['normal message']);
expect(
JSON.parse(state[LOGS_KEY]).map((log) => log.message),
).to.deep.equal(['[unknown] INFO: normal message']);
});
it('filters previously persisted Sub-Store startup banner logs', function () {
const normalLog = {
id: 'normal-log',
time: 2,
level: 'info',
message: 'normal message',
};
state[LOGS_KEY] = JSON.stringify([
{
id: 'banner-log',
time: 1,
level: 'log',
message: SUB_STORE_BANNER,
},
{
id: 'platform-banner-log',
time: 2,
level: 'log',
message: `[sub-store] LOG: ${SUB_STORE_PLATFORM_BANNER}`,
},
{
id: 'unknown-platform-banner-log',
time: 3,
level: 'log',
message: `[unknown] LOG: ${SUB_STORE_PLATFORM_BANNER}`,
},
normalLog,
]);
const result = getLogEntries($, { limit: 10 });
expect(result.logs.map((log) => log.message)).to.deep.equal([
'normal message',
]);
expect(result.total).to.equal(1);
expect(
JSON.parse(state[LOGS_KEY]).map((log) => log.message),
).to.deep.equal(['normal message']);
});
it('filters previously persisted default noisy parser and fallback preprocessor error logs', function () {
state[LOGS_KEY] = JSON.stringify([
...DEFAULT_IGNORED_NOISE_LOGS.map((message, index) => ({
id: `noise-log-${index}`,
time: index + 1,
level: 'info',
message,
})),
{
id: 'normal-log',
time: 4,
level: 'info',
message: 'normal message',
},
]);
const result = getLogEntries($, { limit: 10 });
expect(result.logs.map((log) => log.message)).to.deep.equal([
'normal message',
]);
expect(result.total).to.equal(1);
expect(
JSON.parse(state[LOGS_KEY]).map((log) => log.message),
).to.deep.equal(['normal message']);
});
it('returns recent logs by limit', function () {
appendLogEntry($, 'info', ['one']);
appendLogEntry($, 'info', ['two']);
appendLogEntry($, 'info', ['three']);
const result = getLogEntries($, { limit: 2 });
expect(result.logs.map((log) => log.message)).to.deep.equal([
'[unknown] INFO: three',
'[unknown] INFO: two',
]);
expect(result.total).to.equal(3);
});
it('trims persisted logs when logsMaxCount is reduced', function () {
appendLogEntry($, 'info', ['one']);
appendLogEntry($, 'info', ['two']);
appendLogEntry($, 'info', ['three']);
state[SETTINGS_KEY] = { logsMaxCount: 2 };
const result = getLogEntries($, { limit: 10 });
expect(result.logs.map((log) => log.message)).to.deep.equal([
'[unknown] INFO: three',
'[unknown] INFO: two',
]);
expect(
JSON.parse(state[LOGS_KEY]).map((log) => log.message),
).to.deep.equal(['[unknown] INFO: two', '[unknown] INFO: three']);
});
it('filters logs by keyword', function () {
appendLogEntry($, 'info', ['Alpha message']);
appendLogEntry($, 'error', ['beta message']);
const result = getLogEntries($, { keyword: 'Alpha' });
expect(result.logs).to.have.length(1);
expect(result.logs[0].message).to.equal(
'[unknown] INFO: Alpha message',
);
});
it('supports case-insensitive keyword filtering', function () {
appendLogEntry($, 'info', ['Alpha message']);
appendLogEntry($, 'error', ['beta message']);
const result = getLogEntries($, {
keyword: 'alpha',
ignoreCase: 'true',
});
expect(result.logs).to.have.length(1);
expect(result.logs[0].message).to.equal(
'[unknown] INFO: Alpha message',
);
});
it('supports regular expression keyword filtering', function () {
appendLogEntry($, 'info', ['request GET /api/logs']);
appendLogEntry($, 'warn', ['request POST /api/subs']);
const result = getLogEntries($, {
keyword: 'GET\\s+/api/logs',
regex: 'true',
});
expect(result.logs).to.have.length(1);
expect(result.logs[0].message).to.equal(
'[unknown] INFO: request GET /api/logs',
);
});
it('rejects invalid regular expressions from GET /api/logs', function () {
const getHandler_ = getHandler('GET', '/api/logs');
const getRes = createResponse('/api/logs');
getHandler_(
{
query: {
keyword: '[',
regex: 'true',
},
},
getRes,
);
expect(getRes.statusCode).to.equal(400);
expect(getRes.body.status).to.equal('failed');
expect(getRes.body.error.code).to.equal('INVALID_LOG_KEYWORD_REGEX');
});
it('serves logs from GET /api/logs and clears them with DELETE /api/logs', function () {
appendLogEntry($, 'info', ['route log']);
const getHandler_ = getHandler('GET', '/api/logs');
const getRes = createResponse('/api/logs');
getHandler_({ query: { limit: 10 } }, getRes);
expect(getRes.body.status).to.equal('success');
expect(getRes.body.data.logs).to.have.length(1);
expect(getRes.body.data.logs[0].message).to.equal(
'[unknown] INFO: route log',
);
const deleteHandler = getHandler('DELETE', '/api/logs');
const deleteRes = createResponse('/api/logs');
deleteHandler({ query: {} }, deleteRes);
expect(deleteRes.body.status).to.equal('success');
expect(JSON.parse(state[LOGS_KEY])).to.deep.equal([]);
expect(clearLogEntries).to.be.a('function');
});
});
+333
View File
@@ -0,0 +1,333 @@
import { DEFAULT_LOGS_MAX_COUNT, LOGS_KEY, SETTINGS_KEY } from '@/constants';
const DEFAULT_LOG_LIMIT = 200;
const MAX_LOGS_MAX_COUNT = 10000;
const LOGS_MAX_COUNT_CACHE_TTL_MS = 1000;
const LOG_LEVELS = ['log', 'info', 'warn', 'error', 'debug'];
const DEFAULT_LOG_SCOPE = 'unknown';
const SUB_STORE_BANNER_VERSION_RE = /^Sub-Store\s+--\s+v\d+(?:\.\d+){0,3}$/;
const SUB_STORE_BANNER_SEPARATOR_RE = /^\u2505{8,}$/;
const SUB_STORE_LOG_PREFIX_RE =
/^\[sub-store\]\s+(?:LOG|INFO|WARN|ERROR|DEBUG):\s*/;
const LOG_WITH_SCOPE_AND_LEVEL_PREFIX_RE =
/^\[[^\]\r\n]+\]\s+(?:LOG|INFO|WARN|ERROR|DEBUG):\s*/i;
const LOG_WITH_SCOPE_PREFIX_RE = /^\[([^\]\r\n]+)\]\s*/;
const DEFAULT_IGNORED_SINGLE_LINE_LOG_MESSAGE_RES = [
/^(?:.+\sParser|Rule parser \[.+\]) is activated!?$/,
// /^Pre-processor \[Fallback Base64 Pre-processor\] activated$/,
/^Pre-processor \[.+\] activated!?$/,
/^Fallback Base64 Pre-processor error: decoded line does not start with protocol$/,
];
let consoleCaptureInstalled = false;
let isAppendingConsoleLog = false;
let cachedLogsMaxCount = null;
let cachedLogsMaxCountExpiresAt = 0;
export function normalizeLogLimit(value, fallback = DEFAULT_LOG_LIMIT) {
const normalizedFallback = normalizePositiveInteger(
fallback,
DEFAULT_LOG_LIMIT,
MAX_LOGS_MAX_COUNT,
);
return normalizePositiveInteger(
value,
normalizedFallback,
MAX_LOGS_MAX_COUNT,
);
}
export function normalizeLogsMaxCount(
value,
fallback = DEFAULT_LOGS_MAX_COUNT,
) {
const normalizedFallback = normalizeNonNegativeInteger(
fallback,
DEFAULT_LOGS_MAX_COUNT,
MAX_LOGS_MAX_COUNT,
);
return normalizeNonNegativeInteger(
value,
normalizedFallback,
MAX_LOGS_MAX_COUNT,
);
}
export function formatLogArguments(args) {
return Array.from(args || [])
.map(formatLogValue)
.join(' ');
}
export function readLogEntries($) {
try {
const raw = $.read(LOGS_KEY);
if (!raw) return [];
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!Array.isArray(parsed)) return [];
return parsed.filter(isLogEntry);
} catch {
return [];
}
}
export function persistLogEntries($, logs) {
$.write(JSON.stringify(Array.isArray(logs) ? logs : []), LOGS_KEY);
}
export function appendLogEntry($, level, args) {
try {
const maxCount = getCachedLogsMaxCount($);
if (maxCount === 0) return;
const message = formatLogArguments(args);
if (shouldIgnoreLogMessage(message)) return;
const logs = readLogEntries($);
const normalizedLevel = normalizeLogLevel(level);
logs.push({
id: createLogId(),
time: Date.now(),
level: normalizedLevel,
message: normalizeStoredLogMessage(message, normalizedLevel),
});
persistLogEntries($, logs.slice(-maxCount));
} catch {
// Logging must never break the caller or recursively log failures.
}
}
export function clearLogSettingsCache() {
cachedLogsMaxCount = null;
cachedLogsMaxCountExpiresAt = 0;
}
export function getLogEntries($, query = {}) {
const settings = $.read(SETTINGS_KEY) || {};
const maxCount = normalizeLogsMaxCount(settings.logsMaxCount);
if (maxCount === 0) {
return {
logs: [],
total: 0,
maxCount,
};
}
const limit = normalizeLogLimit(query.limit, maxCount);
const keyword = `${query.keyword || ''}`.trim();
const isRegex = normalizeBooleanQuery(query.regex);
const ignoreCase = normalizeBooleanQuery(query.ignoreCase);
const keywordMatcher = createKeywordMatcher(keyword, {
isRegex,
ignoreCase,
});
let logs = readLogEntries($);
const sanitizedLogs = logs.filter((entry) => !shouldIgnoreLogEntry(entry));
const shouldPersistSanitizedLogs = sanitizedLogs.length !== logs.length;
logs = sanitizedLogs;
if (logs.length > maxCount) {
logs = logs.slice(-maxCount);
persistLogEntries($, logs);
} else if (shouldPersistSanitizedLogs) {
persistLogEntries($, logs);
}
if (keywordMatcher) {
logs = logs.filter((entry) => keywordMatcher(getSearchText(entry)));
}
return {
logs: logs.slice(-limit).reverse(),
total: logs.length,
maxCount,
};
}
export function clearLogEntries($) {
persistLogEntries($, []);
}
export function installConsoleLogCapture($) {
if (consoleCaptureInstalled || typeof console === 'undefined') return;
consoleCaptureInstalled = true;
LOG_LEVELS.forEach((level) => {
const original = console[level];
if (typeof original !== 'function') return;
console[level] = function (...args) {
original.apply(console, args);
if (isAppendingConsoleLog) return;
try {
isAppendingConsoleLog = true;
appendLogEntry($, level, args);
} finally {
isAppendingConsoleLog = false;
}
};
});
}
function normalizePositiveInteger(value, fallback, max) {
const number = Number(value);
if (!isFinite(number) || number <= 0) return fallback;
return Math.min(Math.floor(number), max);
}
function getCachedLogsMaxCount($) {
const now = Date.now();
if (cachedLogsMaxCount !== null && now < cachedLogsMaxCountExpiresAt) {
return cachedLogsMaxCount;
}
const settings = $.read(SETTINGS_KEY) || {};
cachedLogsMaxCount = normalizeLogsMaxCount(settings.logsMaxCount);
cachedLogsMaxCountExpiresAt = now + LOGS_MAX_COUNT_CACHE_TTL_MS;
return cachedLogsMaxCount;
}
function normalizeNonNegativeInteger(value, fallback, max) {
if (value === null || value === undefined || value === '') return fallback;
const number = Number(value);
if (!isFinite(number) || number < 0) return fallback;
return Math.min(Math.floor(number), max);
}
function normalizeBooleanQuery(value) {
return (
value === true ||
value === 1 ||
value === '1' ||
value === 'true' ||
value === 'on'
);
}
function normalizeLogLevel(level) {
return LOG_LEVELS.includes(level) ? level : 'log';
}
function normalizeStoredLogMessage(message, level) {
const rawMessage = `${message || ''}`;
if (LOG_WITH_SCOPE_AND_LEVEL_PREFIX_RE.test(rawMessage)) {
return rawMessage;
}
const normalizedLevel = normalizeLogLevel(level).toUpperCase();
const scopedMatch = rawMessage.match(LOG_WITH_SCOPE_PREFIX_RE);
if (scopedMatch) {
const scope = scopedMatch[1].trim() || DEFAULT_LOG_SCOPE;
const content = rawMessage.slice(scopedMatch[0].length).trimStart();
return `[${scope}] ${normalizedLevel}: ${content}`;
}
return `[${DEFAULT_LOG_SCOPE}] ${normalizedLevel}: ${rawMessage}`;
}
function createKeywordMatcher(keyword, { isRegex, ignoreCase }) {
if (!keyword) return null;
if (isRegex) {
const regexp = new RegExp(keyword, ignoreCase ? 'i' : '');
return (text) => regexp.test(text);
}
const needle = ignoreCase ? keyword.toLowerCase() : keyword;
return (text) => {
const haystack = ignoreCase ? text.toLowerCase() : text;
return haystack.includes(needle);
};
}
function getSearchText(entry) {
return `${entry.level || ''}\n${entry.message || ''}`;
}
function shouldIgnoreLogEntry(entry) {
return shouldIgnoreLogMessage(entry.message);
}
function shouldIgnoreLogMessage(message) {
const lines = getNormalizedLogMessageLines(message);
if (lines.length === 1) {
return (
SUB_STORE_BANNER_VERSION_RE.test(lines[0]) ||
shouldIgnoreSingleLineLogMessage(lines[0])
);
}
return isSubStoreBannerLog(lines);
}
function getNormalizedLogMessageLines(message) {
const lines = `${message || ''}`
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
if (lines.length === 0) return lines;
const firstLineWithoutPrefix = lines[0]
.replace(LOG_WITH_SCOPE_AND_LEVEL_PREFIX_RE, '')
.trim();
if (firstLineWithoutPrefix !== lines[0]) {
if (firstLineWithoutPrefix) {
lines[0] = firstLineWithoutPrefix;
} else {
lines.shift();
}
}
return lines;
}
function isSubStoreBannerLog(lines) {
if (lines.length < 3) return false;
if (!SUB_STORE_BANNER_SEPARATOR_RE.test(lines[0])) return false;
if (!SUB_STORE_BANNER_SEPARATOR_RE.test(lines[lines.length - 1])) {
return false;
}
return lines
.slice(1, -1)
.some((line) => SUB_STORE_BANNER_VERSION_RE.test(line));
}
function shouldIgnoreSingleLineLogMessage(line) {
const normalizedLine = line.replace(SUB_STORE_LOG_PREFIX_RE, '');
return DEFAULT_IGNORED_SINGLE_LINE_LOG_MESSAGE_RES.some((regexp) =>
regexp.test(normalizedLine),
);
}
function formatLogValue(value) {
if (value instanceof Error) {
return value.stack || value.message || String(value);
}
if (typeof value === 'string') return value;
if (value == null) return String(value);
if (typeof value === 'object') {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
return String(value);
}
function isLogEntry(entry) {
return (
entry &&
typeof entry === 'object' &&
typeof entry.id === 'string' &&
typeof entry.time === 'number' &&
typeof entry.level === 'string' &&
typeof entry.message === 'string'
);
}
function createLogId() {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
+1 -1
View File
@@ -351,7 +351,7 @@ export default async function download(
}
}
if (shouldCache) {
console.log($arguments);
// console.log($arguments);
resourceCache.set(
id,
body,
+7
View File
@@ -1,4 +1,6 @@
/* eslint-disable no-undef */
import { installConsoleLogCapture } from '@/utils/debug-logs';
const isQX = typeof $task !== 'undefined';
const isLoon = typeof $loon !== 'undefined';
// 可能有一些兼容环境依赖于这个, 先不改成 $environment.surge-version
@@ -64,6 +66,7 @@ export class OpenAPI {
}
})();
this.initCache();
installConsoleLogCapture(this);
const delay = (t, v) =>
new Promise(function (resolve) {
@@ -350,6 +353,10 @@ export class OpenAPI {
console.log(`[${this.name}] INFO: ${msg}`);
}
warn(msg) {
console.log(`[${this.name}] WARN: ${msg}`);
}
error(msg) {
console.log(`[${this.name}] ERROR: ${msg}`);
}
+6
View File
@@ -395,6 +395,12 @@ function operator(proxies = [], targetPlatform, context) {
// "version": "2.14.198"
// }
// 脚本中使用日志 可以参考这个格式 能在前端日志查看里区分识别
// console.log(`[SCOPE] LOG: 信息`)
// console.log(`[SCOPE] INFO: 信息`)
// console.log(`[SCOPE] WARN: 警告`)
// console.log(`[SCOPE] ERROR: 错误`)
// 参数说明
// 可参考 https://github.com/sub-store-org/Sub-Store/wiki/%E9%93%BE%E6%8E%A5%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E