【m】log完成

This commit is contained in:
2026-05-06 16:08:00 +08:00
parent e47eee39ed
commit a6cda3e9dd
7 changed files with 70 additions and 42 deletions

View File

@@ -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) {

View File

@@ -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<string>();
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<WebSocket>() });
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);
}

View File

@@ -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[] {

View File

@@ -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<string, LogLevel> = {
'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;
}
}

View File

@@ -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: '文件重命名失败' });
}

View File

@@ -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 查看`);
};

View File

@@ -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) {