feat: add SLS toggle and sanitize logs

This commit is contained in:
empty
2025-12-27 15:07:28 +08:00
parent b186f9b80e
commit 5e01993120
5 changed files with 139 additions and 24 deletions

View File

@@ -8,6 +8,7 @@
*/
import ALSClient from 'aliyun-log';
import { sanitizeForLog } from './log-sanitizer.js';
// SLS 配置
const SLS_CONFIG = {
@@ -18,8 +19,22 @@ const SLS_CONFIG = {
logstore: process.env.ALIYUN_SLS_LOGSTORE
};
function resolveSlsEnabled() {
const raw = process.env.SLS_ENABLED;
if (raw === undefined || raw === null || String(raw).trim() === '') {
return process.env.NODE_ENV !== 'production';
}
const value = String(raw).trim().toLowerCase();
if (['1', 'true', 'yes', 'on'].includes(value)) return true;
if (['0', 'false', 'no', 'off'].includes(value)) return false;
return process.env.NODE_ENV !== 'production';
}
const SLS_ENABLED = resolveSlsEnabled();
// 检查配置是否完整
const isConfigured = Object.values(SLS_CONFIG).every(v => v);
const isConfigured = SLS_ENABLED && Object.values(SLS_CONFIG).every(v => v);
let client = null;
let logQueue = [];
@@ -28,6 +43,9 @@ const FLUSH_INTERVAL_MS = 5000;
// 初始化 SLS Client
function initClient() {
if (!SLS_ENABLED) {
return null;
}
if (!isConfigured) {
console.warn('[SLS] 阿里云日志服务未配置,日志将仅输出到控制台');
return null;
@@ -73,7 +91,7 @@ async function flushLogs() {
// 定时刷新
let flushTimer = null;
function startFlushTimer() {
if (flushTimer || !isConfigured) return;
if (!SLS_ENABLED || flushTimer || !isConfigured) return;
flushTimer = setInterval(flushLogs, FLUSH_INTERVAL_MS);
}
@@ -90,10 +108,11 @@ function startFlushTimer() {
* @param {string} [logData.error] - 错误信息
*/
export function logRequest(logData) {
const enrichedLog = {
if (!SLS_ENABLED) return;
const enrichedLog = sanitizeForLog({
timestamp: new Date().toISOString(),
...logData
};
});
// 始终输出到控制台
console.log('[SLS]', JSON.stringify(enrichedLog));
@@ -112,6 +131,7 @@ export function logRequest(logData) {
* 优雅关闭,刷新剩余日志
*/
export async function shutdown() {
if (!SLS_ENABLED) return;
if (flushTimer) {
clearInterval(flushTimer);
flushTimer = null;