Skip to content

Commit

Permalink
feat: add BrowserLogger with configurable log levels
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Willenbring committed Sep 7, 2023
1 parent 42b22d0 commit 663b81b
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 13 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion documentation/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ $ npm install

## Create .env file

Create a `.env` file and simply copy the content of `.env.dev` into it.
Create a `.env` file and simply copy the content of `.env.template` into it.
The `.env` file should contain everything required to start the application locally.

## Run dev servers
Expand Down
7 changes: 7 additions & 0 deletions packages/frontend/src/common/hooks/useLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { useConfigurationContext } from "../context/ConfigurationContext";
import { BrowserLogger } from "@shared/logger/dist/browserLogger";

export function useLogger() {
const { logLevel } = useConfigurationContext();
return new BrowserLogger({ level: logLevel });
}
18 changes: 10 additions & 8 deletions packages/frontend/src/common/hooks/usePeerToPeer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { useIsStateUpToDate } from "./useIsStateUpToDate";
import { findConnection, findUnconnectedUserIds } from "../utils/peerToPeerUtils";
import { usePeer } from "./usePeer";
import { isEmpty } from "lodash";
import { useLogger } from "./useLogger";

export interface UsePeerToPeerOptions<T, E extends BaseAction> {
state: T;
Expand Down Expand Up @@ -46,6 +47,7 @@ export function usePeerToPeer<T, E extends BaseAction>({
usePeerConnections({
onPeerConnectionReady: handlePeerConnectionReady,
});
const logger = useLogger();

function handlePeerConnectionReady(changes: PeerConnection[]) {
if (!isModerator(user) || !isStateUpToDate.current) return;
Expand All @@ -59,14 +61,14 @@ export function usePeerToPeer<T, E extends BaseAction>({
const connection = findConnection(peerConnections, userId);
if (!connection) return;

console.debug("Sending event", { event, userId });
logger.debug("Sending event", { event, userId });
connection.send(event);
}

function broadcastAction(action: E | PeerToPeerAction<T>) {
if (isEmpty(peerConnections)) return;

console.debug("Broadcasting action", action);
logger.debug("Broadcasting action", action);
peerConnections.forEach((connection) => {
connection.send(action);
});
Expand All @@ -77,7 +79,7 @@ export function usePeerToPeer<T, E extends BaseAction>({
onUserDisconnected?.(disconnectedUserId);
if (!closingConnection) return;

console.debug("Closing connection to", closingConnection.peer);
logger.debug("Closing connection to", closingConnection.peer);
closingConnection.close();
removePeerConnection(closingConnection.peer);
}
Expand All @@ -90,21 +92,21 @@ export function usePeerToPeer<T, E extends BaseAction>({
connectedUserId: string;
}) {
if (!peer) return;
console.debug("New user connected", {
logger.debug("New user connected", {
connectedUserIds,
connectedUserId,
userId: user.id,
});

const unconnectedUserIds = findUnconnectedUserIds(connectedUserIds, user.id, peerConnections);
if (unconnectedUserIds.length === 0) {
console.debug("Connection to all users already established.");
logger.debug("Connection to all users already established.");
return;
}

const newConnections = unconnectedUserIds.map((id) => peer.connect(id, { reliable: true }));

console.debug("Peer-Connections established with users:", unconnectedUserIds);
logger.debug("Peer-Connections established with users:", unconnectedUserIds);
addPeerConnection(newConnections);
}

Expand All @@ -120,7 +122,7 @@ export function usePeerToPeer<T, E extends BaseAction>({
}

function handleOnData(data: E | PeerToPeerAction<T>) {
console.debug("Received event", data);
logger.debug("Received event", data);
onDataReceived(data);

if (data.type === "KICK") {
Expand Down Expand Up @@ -184,7 +186,7 @@ export function usePeerToPeer<T, E extends BaseAction>({
});

peer?.on("error", (error) => {
console.debug("Peer Connection Error: ", error);
logger.debug("Peer Connection Error: ", error);
});

return () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/frontend/src/common/hooks/useSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ import { ClientToServerEvents, ServerToClientEvents } from "@shared/socket";
import { useUserContext } from "../context/UserContext";
import { useRoomContext } from "../context/RoomContext";
import { useConfigurationContext } from "../context/ConfigurationContext";
import { useLogger } from "./useLogger";

export function useSocket() {
const { url: backendUrl } = useConfigurationContext().backendUrl;
const { user } = useUserContext();
const { roomId } = useRoomContext();
const socketNamespace = useNamespace();
const logger = useLogger();

const socket = useMemo(() => {
console.debug(`Established socket connection with: ${backendUrl}`);
logger.debug(`Established socket connection with: ${backendUrl}`);
return io(`${backendUrl}/${socketNamespace}`) as Socket<
ServerToClientEvents,
ClientToServerEvents
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/configuration/src/configuration.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApplicationConfiguration, CorsOrigins } from "./types";
import { ApplicationConfiguration, CorsOrigins, LogLevel } from "./types";
import { RetroAppUrl } from "./RetroAppUrl";

export const configuration = getConfiguration();
Expand All @@ -17,7 +17,7 @@ function getConfiguration(): ApplicationConfiguration {
});

return {
logLevel: process.env.LOG_LEVEL ?? "info",
logLevel: validateLogLevel(process.env.LOG_LEVEL) ?? "info",
backendUrl,
signalingServerUrl,
retro: {
Expand All @@ -34,3 +34,10 @@ function parseCorsOrigins(list?: string): CorsOrigins | undefined {
if (origins.length <= 1) return list;
return origins;
}

function validateLogLevel(logLevel?: string): LogLevel | undefined {
const validLogLevels: LogLevel[] = ["debug", "info", "warn", "error"];
if (logLevel && !validLogLevels.some((level) => level === logLevel))
throw Error(`Invalid log level '${logLevel}'. Allowed levels: ${validLogLevels}`);
return logLevel as LogLevel;
}
4 changes: 3 additions & 1 deletion packages/shared/configuration/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { RetroAppUrl } from "./RetroAppUrl";

export type CorsOrigins = string | string[];

export type LogLevel = "info" | "warn" | "error" | "debug";

export interface ApplicationConfiguration {
logLevel: string;
logLevel: LogLevel;
backendUrl: RetroAppUrl;
retro: RetroConfiguration;
signalingServerUrl: RetroAppUrl;
Expand Down
50 changes: 50 additions & 0 deletions packages/shared/logger/src/BrowserLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { LogLevel } from "@shared/configuration";

export type LogFn = (message?: any, ...optionalParams: any[]) => void;

export interface Logger {
debug: LogFn;
info: LogFn;
warn: LogFn;
error: LogFn;
}

export interface BrowserLoggerOptions {
level?: LogLevel;
}

const NO_OP: LogFn = (_message?: any, ..._optionalParams: any[]) => {};

export class BrowserLogger implements Logger {
readonly debug: LogFn;
readonly info: LogFn;
readonly warn: LogFn;
readonly error: LogFn;

constructor(options?: BrowserLoggerOptions) {
const { level } = options ?? {};

this.error = console.error.bind(console);
if (level === "error") {
this.warn = NO_OP;
this.info = NO_OP;
this.debug = NO_OP;
return;
}

this.warn = console.warn.bind(console);
if (level === "warn") {
this.info = NO_OP;
this.debug = NO_OP;
return;
}

this.info = console.info.bind(console);
if (level === "info") {
this.debug = NO_OP;
return;
}

this.debug = console.debug.bind(console);
}
}
1 change: 1 addition & 0 deletions packages/shared/logger/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./logger";
export * from "./BrowserLogger";

0 comments on commit 663b81b

Please sign in to comment.