【m】log完成
This commit is contained in:
@@ -8,6 +8,7 @@ import Answer from './answer';
|
|||||||
import Candidate from './candidate';
|
import Candidate from './candidate';
|
||||||
import { v4 as uuid } from 'uuid';
|
import { v4 as uuid } from 'uuid';
|
||||||
import { onGetAllConnectionIds } from './websockethandler';
|
import { onGetAllConnectionIds } from './websockethandler';
|
||||||
|
import { log, LogLevel } from '../log';
|
||||||
/**
|
/**
|
||||||
* 断开连接记录类
|
* 断开连接记录类
|
||||||
* 用于记录断开连接的信息
|
* 用于记录断开连接的信息
|
||||||
@@ -226,7 +227,7 @@ function _checkForTimedOutSessions(): void {
|
|||||||
continue;
|
continue;
|
||||||
// 删除超时会话
|
// 删除超时会话
|
||||||
_deleteSession(sessionId);
|
_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是否已被使用
|
// 检查连接ID是否已被使用
|
||||||
if (pair[0] != null && pair[1] != null) {
|
if (pair[0] != null && pair[1] != null) {
|
||||||
const err = new Error(`${connectionId}: This connection id is already used.`);
|
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 });
|
res.status(400).send({ error: err });
|
||||||
return;
|
return;
|
||||||
} else if (pair[0] != null) {
|
} else if (pair[0] != null) {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
import Offer from './offer';
|
import Offer from './offer';
|
||||||
import Answer from './answer';
|
import Answer from './answer';
|
||||||
import Candidate from './candidate';
|
import Candidate from './candidate';
|
||||||
|
import { log, LogLevel } from '../log';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 是否为私有模式
|
* 是否为私有模式
|
||||||
@@ -73,7 +74,7 @@ function add(ws: WebSocket): void {
|
|||||||
const id = new Set<string>();
|
const id = new Set<string>();
|
||||||
clients.set(ws, id);
|
clients.set(ws, id);
|
||||||
// 记录添加WebSocket连接的日志
|
// 记录添加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 }));
|
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);
|
clients.delete(ws);
|
||||||
@@ -150,13 +151,13 @@ function onConnect(ws: WebSocket, connectionId: string): void {
|
|||||||
if (connectionGroup.has(connectionId)) {
|
if (connectionGroup.has(connectionId)) {
|
||||||
const group = connectionGroup.get(connectionId);
|
const group = connectionGroup.get(connectionId);
|
||||||
group.participants.add(ws);
|
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加入
|
// 通知host有新participant加入
|
||||||
group.host.send(JSON.stringify({ type: "participant-joined", connectionId: connectionId, participantId: participantId }));
|
group.host.send(JSON.stringify({ type: "participant-joined", connectionId: connectionId, participantId: participantId }));
|
||||||
} else {
|
} else {
|
||||||
connectionGroup.set(connectionId, { host: ws, participants: new Set<WebSocket>() });
|
connectionGroup.set(connectionId, { host: ws, participants: new Set<WebSocket>() });
|
||||||
polite = false;
|
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" }));
|
participantWs.send(JSON.stringify({ type: "disconnect", connectionId: connectionId, reason: "host-left" }));
|
||||||
});
|
});
|
||||||
connectionGroup.delete(connectionId);
|
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 {
|
} else {
|
||||||
// participant断开连接,从组中移除并通知host(使用participant-left类型,host不会关闭房间)
|
// participant断开连接,从组中移除并通知host(使用participant-left类型,host不会关闭房间)
|
||||||
group.participants.delete(ws);
|
group.participants.delete(ws);
|
||||||
group.host.send(JSON.stringify({ type: "participant-left", connectionId: connectionId, participantId: (ws as any).participantId }));
|
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 }));
|
ws.send(JSON.stringify({ type: "disconnect", connectionId: connectionId }));
|
||||||
//RemoveHeartbeat(ws);
|
//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();
|
const now = Date.now();
|
||||||
// 检查上次活动时间,如果超过60秒没有活动,关闭连接
|
// 检查上次活动时间,如果超过60秒没有活动,关闭连接
|
||||||
if (now - (ws as any).lastActivity > 10000) {
|
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);
|
clearInterval((ws as any).heartbeatTimer);
|
||||||
//ws.close();
|
//ws.close();
|
||||||
onDisconnect(ws, connectionId);
|
onDisconnect(ws, connectionId);
|
||||||
} else {
|
} else {
|
||||||
// 发送ping消息
|
// 发送ping消息
|
||||||
ws.send(JSON.stringify({ from: connectionId, to: "", type: "on-message", data: { type: "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);
|
}, 3000);
|
||||||
}
|
}
|
||||||
|
|||||||
15
src/index.ts
15
src/index.ts
@@ -8,6 +8,7 @@ import { createServer } from './server';
|
|||||||
import { AddressInfo } from 'net';
|
import { AddressInfo } from 'net';
|
||||||
import WSSignaling from './websocket';
|
import WSSignaling from './websocket';
|
||||||
import Options from './class/options';
|
import Options from './class/options';
|
||||||
|
import { log, LogLevel } from './log';
|
||||||
|
|
||||||
export class RenderStreaming {
|
export class RenderStreaming {
|
||||||
public static run(argv: string[]): RenderStreaming {
|
public static run(argv: string[]): RenderStreaming {
|
||||||
@@ -59,7 +60,7 @@ export class RenderStreaming {
|
|||||||
const { port } = this.server.address() as AddressInfo;
|
const { port } = this.server.address() as AddressInfo;
|
||||||
const addresses = this.getIPAddress();
|
const addresses = this.getIPAddress();
|
||||||
for (const address of addresses) {
|
for (const address of addresses) {
|
||||||
console.log(`https://${address}:${port}`);
|
log(LogLevel.info, `https://${address}:${port}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -67,26 +68,26 @@ export class RenderStreaming {
|
|||||||
const { port } = this.server.address() as AddressInfo;
|
const { port } = this.server.address() as AddressInfo;
|
||||||
const addresses = this.getIPAddress();
|
const addresses = this.getIPAddress();
|
||||||
for (const address of addresses) {
|
for (const address of addresses) {
|
||||||
console.log(`http://${address}:${port}`);
|
log(LogLevel.info, `http://${address}:${port}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (this.options.type == 'http') {
|
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') {
|
else if(this.options.type != 'websocket') {
|
||||||
console.log(`signaling type should be set "websocket" or "http". ${this.options.type} is not supported.`);
|
log(LogLevel.warn, `signaling type should be set "websocket" or "http". ${this.options.type} is not supported.`);
|
||||||
console.log(`Changing signaling type to websocket.`);
|
log(LogLevel.warn, `Changing signaling type to websocket.`);
|
||||||
this.options.type = 'websocket';
|
this.options.type = 'websocket';
|
||||||
}
|
}
|
||||||
if (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
|
//Start Websocket Signaling server
|
||||||
new WSSignaling(this.server, this.options.mode);
|
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[] {
|
getIPAddress(): string[] {
|
||||||
|
|||||||
55
src/log.ts
55
src/log.ts
@@ -1,27 +1,50 @@
|
|||||||
const isDebug = true;
|
|
||||||
|
|
||||||
export enum LogLevel {
|
export enum LogLevel {
|
||||||
info,
|
none = -1,
|
||||||
log,
|
error = 0,
|
||||||
warn,
|
warn = 1,
|
||||||
error,
|
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 {
|
export function log(level: LogLevel, ...args: any[]): void {
|
||||||
if (isDebug) {
|
if (level > logLevel || logLevel === LogLevel.none) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timestamp = formatTimestamp();
|
||||||
|
const prefix = `[${timestamp}] [${LogLevel[level].toUpperCase()}]`;
|
||||||
switch (level) {
|
switch (level) {
|
||||||
case LogLevel.log:
|
case LogLevel.error:
|
||||||
console.log(...args);
|
console.error(prefix, ...args);
|
||||||
break;
|
|
||||||
case LogLevel.info:
|
|
||||||
console.info(...args);
|
|
||||||
break;
|
break;
|
||||||
case LogLevel.warn:
|
case LogLevel.warn:
|
||||||
console.warn(...args);
|
console.warn(prefix, ...args);
|
||||||
break;
|
break;
|
||||||
case LogLevel.error:
|
case LogLevel.info:
|
||||||
console.error(...args);
|
console.info(prefix, ...args);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.log(prefix, ...args);
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export const createServer = (config: Options): express.Express => {
|
|||||||
// 重命名文件
|
// 重命名文件
|
||||||
fs.rename(oldPath, newPath, (err) => {
|
fs.rename(oldPath, newPath, (err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error('Error renaming file:', err);
|
log(LogLevel.error, 'Error renaming file:', err);
|
||||||
return res.status(500).json({ success: false, message: '文件重命名失败' });
|
return res.status(500).json({ success: false, message: '文件重命名失败' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import * as swaggerJSDoc from 'swagger-jsdoc';
|
|||||||
import * as swaggerUi from 'swagger-ui-express';
|
import * as swaggerUi from 'swagger-ui-express';
|
||||||
import { Express } from 'express';
|
import { Express } from 'express';
|
||||||
import Options from './class/options';
|
import Options from './class/options';
|
||||||
|
import { log, LogLevel } from './log';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 初始化Swagger
|
* 初始化Swagger
|
||||||
@@ -60,5 +61,5 @@ export const initSwagger = (app: Express, config: Options): void => {
|
|||||||
|
|
||||||
const swaggerSpec = swaggerJSDoc(swaggerOptions);
|
const swaggerSpec = swaggerJSDoc(swaggerOptions);
|
||||||
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
|
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
|
||||||
console.log(`Swagger文档已初始化,访问 ${serverUrl}/api-docs 查看`);
|
log(LogLevel.info, `Swagger文档已初始化,访问 ${serverUrl}/api-docs 查看`);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as websocket from "ws";
|
import * as websocket from "ws";
|
||||||
import { Server } from 'http';
|
import { Server } from 'http';
|
||||||
import * as handler from "./class/websockethandler";
|
import * as handler from "./class/websockethandler";
|
||||||
|
import { log, LogLevel } from './log';
|
||||||
|
|
||||||
export default class WSSignaling {
|
export default class WSSignaling {
|
||||||
server: Server;
|
server: Server;
|
||||||
@@ -69,7 +70,7 @@ export default class WSSignaling {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 打印接收到的消息
|
// 打印接收到的消息
|
||||||
console.log(msg);
|
log(LogLevel.log, 'WS received:', msg);
|
||||||
|
|
||||||
// 根据消息类型处理
|
// 根据消息类型处理
|
||||||
switch (msg.type) {
|
switch (msg.type) {
|
||||||
|
|||||||
Reference in New Issue
Block a user