From a6cda3e9dd34c796dcbc1229881a85858a4561af Mon Sep 17 00:00:00 2001 From: stary <834207172@qq.COM> Date: Wed, 6 May 2026 16:08:00 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90m=E3=80=91log=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/class/httphandler.ts | 5 +-- src/class/websockethandler.ts | 19 +++++----- src/index.ts | 15 ++++---- src/log.ts | 65 ++++++++++++++++++++++++----------- src/server.ts | 2 +- src/swagger.ts | 3 +- src/websocket.ts | 3 +- 7 files changed, 70 insertions(+), 42 deletions(-) diff --git a/src/class/httphandler.ts b/src/class/httphandler.ts index c5b65b0..e374ed5 100644 --- a/src/class/httphandler.ts +++ b/src/class/httphandler.ts @@ -8,6 +8,7 @@ import Answer from './answer'; import Candidate from './candidate'; import { v4 as uuid } from 'uuid'; import { onGetAllConnectionIds } from './websockethandler'; +import { log, LogLevel } from '../log'; /** * 断开连接记录类 * 用于记录断开连接的信息 @@ -226,7 +227,7 @@ function _checkForTimedOutSessions(): void { continue; // 删除超时会话 _deleteSession(sessionId); - console.log(`deleted sessionId:${sessionId} by timeout.`); + log(LogLevel.log, `deleted sessionId:${sessionId} by timeout.`); } } @@ -757,7 +758,7 @@ function createConnection(req: Request, res: Response): void { // 检查连接ID是否已被使用 if (pair[0] != null && pair[1] != null) { const err = new Error(`${connectionId}: This connection id is already used.`); - console.log(err); + log(LogLevel.warn, err.message); res.status(400).send({ error: err }); return; } else if (pair[0] != null) { diff --git a/src/class/websockethandler.ts b/src/class/websockethandler.ts index 675fb1d..87470d8 100644 --- a/src/class/websockethandler.ts +++ b/src/class/websockethandler.ts @@ -5,6 +5,7 @@ import Offer from './offer'; import Answer from './answer'; import Candidate from './candidate'; +import { log, LogLevel } from '../log'; /** * 是否为私有模式 @@ -73,7 +74,7 @@ function add(ws: WebSocket): void { const id = new Set(); clients.set(ws, id); // 记录添加WebSocket连接的日志 - console.log(`Add WebSocket: ${ws.url}`); + log(LogLevel.log, `Add WebSocket: ${ws.url}`); } /** @@ -129,7 +130,7 @@ function remove(ws: WebSocket): void { group.host.send(JSON.stringify({ type: "participant-left", connectionId: connectionId, participantId: (ws as any).participantId })); } } - console.log(`Remove connectionId: ${connectionId}`); + log(LogLevel.log, `Remove connectionId: ${connectionId}`); }); clients.delete(ws); @@ -150,13 +151,13 @@ function onConnect(ws: WebSocket, connectionId: string): void { if (connectionGroup.has(connectionId)) { const group = connectionGroup.get(connectionId); group.participants.add(ws); - console.log(`Participant ${participantId} joined connectionId: ${connectionId}, total participants: ${group.participants.size}`); + log(LogLevel.log, `Participant ${participantId} joined connectionId: ${connectionId}, total participants: ${group.participants.size}`); // 通知host有新participant加入 group.host.send(JSON.stringify({ type: "participant-joined", connectionId: connectionId, participantId: participantId })); } else { connectionGroup.set(connectionId, { host: ws, participants: new Set() }); polite = false; - console.log(`Host created connectionId: ${connectionId}`); + log(LogLevel.log, `Host created connectionId: ${connectionId}`); } } @@ -188,12 +189,12 @@ function onDisconnect(ws: WebSocket, connectionId: string): void { participantWs.send(JSON.stringify({ type: "disconnect", connectionId: connectionId, reason: "host-left" })); }); connectionGroup.delete(connectionId); - console.log(`Host disconnected, room ${connectionId} deleted, notified ${group.participants.size} participants`); + log(LogLevel.log, `Host disconnected, room ${connectionId} deleted, notified ${group.participants.size} participants`); } else { // participant断开连接,从组中移除并通知host(使用participant-left类型,host不会关闭房间) group.participants.delete(ws); group.host.send(JSON.stringify({ type: "participant-left", connectionId: connectionId, participantId: (ws as any).participantId })); - console.log(`Participant left connectionId: ${connectionId}, remaining participants: ${group.participants.size}`); + log(LogLevel.log, `Participant left connectionId: ${connectionId}, remaining participants: ${group.participants.size}`); } } @@ -201,7 +202,7 @@ function onDisconnect(ws: WebSocket, connectionId: string): void { ws.send(JSON.stringify({ type: "disconnect", connectionId: connectionId })); //RemoveHeartbeat(ws); // 记录断开连接的日志 - console.log(`Disconnect connectionId: ${connectionId}`); + log(LogLevel.log, `Disconnect connectionId: ${connectionId}`); } /** @@ -409,14 +410,14 @@ function AddHeartbeat(ws: WebSocket, connectionId: string) { const now = Date.now(); // 检查上次活动时间,如果超过60秒没有活动,关闭连接 if (now - (ws as any).lastActivity > 10000) { - console.log('WebSocket connection timeout, closing...'); + log(LogLevel.warn, 'WebSocket connection timeout, closing...'); clearInterval((ws as any).heartbeatTimer); //ws.close(); onDisconnect(ws, connectionId); } else { // 发送ping消息 ws.send(JSON.stringify({ from: connectionId, to: "", type: "on-message", data: { type: "ping"} })); - console.log('WebSocket connection heartbeat, lastActivity: ', (ws as any).lastActivity); + log(LogLevel.log, 'WebSocket connection heartbeat, lastActivity: ', (ws as any).lastActivity); } }, 3000); } diff --git a/src/index.ts b/src/index.ts index 7e4b4cb..a8df87d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ import { createServer } from './server'; import { AddressInfo } from 'net'; import WSSignaling from './websocket'; import Options from './class/options'; +import { log, LogLevel } from './log'; export class RenderStreaming { public static run(argv: string[]): RenderStreaming { @@ -59,7 +60,7 @@ export class RenderStreaming { const { port } = this.server.address() as AddressInfo; const addresses = this.getIPAddress(); for (const address of addresses) { - console.log(`https://${address}:${port}`); + log(LogLevel.info, `https://${address}:${port}`); } }); } else { @@ -67,26 +68,26 @@ export class RenderStreaming { const { port } = this.server.address() as AddressInfo; const addresses = this.getIPAddress(); for (const address of addresses) { - console.log(`http://${address}:${port}`); + log(LogLevel.info, `http://${address}:${port}`); } }); } if (this.options.type == 'http') { - console.log(`Use http polling for signaling server.`); + log(LogLevel.info, `Use http polling for signaling server.`); } else if(this.options.type != 'websocket') { - console.log(`signaling type should be set "websocket" or "http". ${this.options.type} is not supported.`); - console.log(`Changing signaling type to websocket.`); + log(LogLevel.warn, `signaling type should be set "websocket" or "http". ${this.options.type} is not supported.`); + log(LogLevel.warn, `Changing signaling type to websocket.`); this.options.type = 'websocket'; } if (this.options.type == 'websocket') { - console.log(`Use websocket for signaling server ws://${this.getIPAddress()[0]}`); + log(LogLevel.info, `Use websocket for signaling server ws://${this.getIPAddress()[0]}`); //Start Websocket Signaling server new WSSignaling(this.server, this.options.mode); } - console.log(`start as ${this.options.mode} mode`); + log(LogLevel.info, `Start as ${this.options.mode} mode`); } getIPAddress(): string[] { diff --git a/src/log.ts b/src/log.ts index 6268c02..3ee2f57 100644 --- a/src/log.ts +++ b/src/log.ts @@ -1,27 +1,50 @@ -const isDebug = true; - export enum LogLevel { - info, - log, - warn, - error, + none = -1, + error = 0, + warn = 1, + log = 2, + info = 3, +} + +let logLevel: LogLevel = LogLevel.info; + +export function setLogLevel(level: LogLevel): void { + logLevel = level; +} + +export function parseLogLevel(levelStr: string): LogLevel { + const map: Record = { + 'none': LogLevel.none, + 'error': LogLevel.error, + 'warn': LogLevel.warn, + 'log': LogLevel.log, + 'info': LogLevel.info, + }; + return map[levelStr.toLowerCase()] ?? LogLevel.info; +} + +function formatTimestamp(): string { + return new Date().toISOString(); } export function log(level: LogLevel, ...args: any[]): void { - if (isDebug) { - switch (level) { - case LogLevel.log: - console.log(...args); - break; - case LogLevel.info: - console.info(...args); - break; - case LogLevel.warn: - console.warn(...args); - break; - case LogLevel.error: - console.error(...args); - break; - } + if (level > logLevel || logLevel === LogLevel.none) { + return; + } + const timestamp = formatTimestamp(); + const prefix = `[${timestamp}] [${LogLevel[level].toUpperCase()}]`; + switch (level) { + case LogLevel.error: + console.error(prefix, ...args); + break; + case LogLevel.warn: + console.warn(prefix, ...args); + break; + case LogLevel.info: + console.info(prefix, ...args); + break; + default: + console.log(prefix, ...args); + break; } } diff --git a/src/server.ts b/src/server.ts index e2d6171..4094e12 100644 --- a/src/server.ts +++ b/src/server.ts @@ -73,7 +73,7 @@ export const createServer = (config: Options): express.Express => { // 重命名文件 fs.rename(oldPath, newPath, (err) => { if (err) { - console.error('Error renaming file:', err); + log(LogLevel.error, 'Error renaming file:', err); return res.status(500).json({ success: false, message: '文件重命名失败' }); } diff --git a/src/swagger.ts b/src/swagger.ts index 0f2e16e..f7c0685 100644 --- a/src/swagger.ts +++ b/src/swagger.ts @@ -6,6 +6,7 @@ import * as swaggerJSDoc from 'swagger-jsdoc'; import * as swaggerUi from 'swagger-ui-express'; import { Express } from 'express'; import Options from './class/options'; +import { log, LogLevel } from './log'; /** * 初始化Swagger @@ -60,5 +61,5 @@ export const initSwagger = (app: Express, config: Options): void => { const swaggerSpec = swaggerJSDoc(swaggerOptions); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); - console.log(`Swagger文档已初始化,访问 ${serverUrl}/api-docs 查看`); + log(LogLevel.info, `Swagger文档已初始化,访问 ${serverUrl}/api-docs 查看`); }; diff --git a/src/websocket.ts b/src/websocket.ts index f92285c..7c5f4c8 100644 --- a/src/websocket.ts +++ b/src/websocket.ts @@ -1,6 +1,7 @@ import * as websocket from "ws"; import { Server } from 'http'; import * as handler from "./class/websockethandler"; +import { log, LogLevel } from './log'; export default class WSSignaling { server: Server; @@ -69,7 +70,7 @@ export default class WSSignaling { } // 打印接收到的消息 - console.log(msg); + log(LogLevel.log, 'WS received:', msg); // 根据消息类型处理 switch (msg.type) {