use structed logging

This commit is contained in:
evanpelle
2024-09-01 12:51:20 -07:00
parent 735a2ae57b
commit 026a0cddbe
10 changed files with 292 additions and 31 deletions
+5 -1
View File
@@ -3,5 +3,9 @@ import {ClientID} from '../core/Schemas';
export class Client {
constructor(public readonly id: ClientID, public readonly ws: WebSocket) { }
constructor(
public readonly id: ClientID,
public readonly ip: string | null,
public readonly ws: WebSocket
) { }
}
+7
View File
@@ -2,6 +2,7 @@ import {ClientMessage, ClientMessageSchema, Intent, ServerStartGameMessage, Serv
import {Config} from "../core/configuration/Config";
import {Client} from "./Client";
import WebSocket from 'ws';
import {slog} from "./StructuredLog";
export enum GamePhase {
@@ -30,6 +31,12 @@ export class GameServer {
public addClient(client: Client, lastTurn: number) {
console.log(`game ${this.id} adding client ${client.id}`)
slog('client_joined_game', `client ${client.id} (re)joining game ${this.id}`, {
clientID: client.id,
clientIP: client.ip,
gameID: this.id,
isRejoin: lastTurn > 0
})
// Remove stale client if this is a reconnect
this.clients = this.clients.filter(c => c.id != client.id)
this.clients.push(client)
+3 -3
View File
@@ -8,6 +8,7 @@ import {Client} from './Client';
import {ClientMessage, ClientMessageSchema} from '../core/Schemas';
import {GamePhase} from './GameServer';
import {getConfig} from '../core/configuration/Config';
import {LogSeverity, slog} from './StructuredLog';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -31,11 +32,10 @@ app.get('/lobbies', (req, res) => {
wss.on('connection', (ws) => {
ws.on('message', (message: string) => {
console.log(`got message ${message}`)
const clientMsg: ClientMessage = ClientMessageSchema.parse(JSON.parse(message))
slog('websocket_msg', 'server received websocket message', clientMsg, LogSeverity.DEBUG)
if (clientMsg.type == "join") {
console.log('got join request')
gm.addClient(new Client(clientMsg.clientID, ws), clientMsg.gameID, clientMsg.lastTurn)
gm.addClient(new Client(clientMsg.clientID, clientMsg.clientIP, ws), clientMsg.gameID, clientMsg.lastTurn)
}
// TODO: send error message
})
+21
View File
@@ -0,0 +1,21 @@
export enum LogSeverity {
DEBUG = 'DEBUG',
INFO = 'INFO',
WARN = 'WARN',
ERROR = 'ERROR',
FATAL = 'FATAL'
}
export function slog(eventType: string, description, data: any, severity = LogSeverity.INFO): void {
const logEntry = {
eventType: eventType,
description: description,
severity: severity,
data: data
};
if (process.env.GAME_ENV == 'dev') {
console.log(description)
} else {
console.log(JSON.stringify(logEntry));
}
}