Skip to content

Commit 4506ce3

Browse files
committed
feat(logger): Implement configurable logging and replace console statements in client SDK
This commit introduces a new logging utility to the microstream-client SDK, allowing developers to control the verbosity of logs using a configurable logLevel option. The logLevel supports the following levels: "debug", "info", "warn", "error", and "silent". Changes include: - Creation of a logger.ts file in src/utils/ with methods for debug, info, warn, and error, respecting the logLevel setting. - Addition of a logLevel option to the MicrostreamClientOptions interface. - Initialization of the logger in the MicrostreamClient constructor using the provided logLevel. - Replacement of all console.log, console.warn, and console.error calls with the appropriate logger methods.
1 parent c10ec70 commit 4506ce3

File tree

5 files changed

+88
-19
lines changed

5 files changed

+88
-19
lines changed

README.md

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
# Microstream Client SDK
32

43
A lightweight client SDK for Microstream communication.
@@ -17,13 +16,34 @@ import { MicrostreamClient } from "microstream-client";
1716
const client = new MicrostreamClient({
1817
hubUrl: "http://localhost:3000",
1918
serviceName: "auth-service",
19+
logLevel: "debug", // Enable debug logs
2020
});
2121

2222
client.onRequest("authenticate", (data) => {
2323
console.log("Received authentication request:", data);
2424
return { success: true, token: "sample-token" };
2525
});
2626

27-
const response = await client.sendRequest("jwt-service", "generate_jwt", { userId: 123 });
27+
const response = await client.sendRequest("jwt-service", "generate_jwt", {
28+
userId: 123,
29+
});
2830
console.log("Received response:", response);
2931
```
32+
33+
### Configuration Options
34+
35+
#### MicrostreamClientOptions
36+
37+
- `hubUrl`: URL of the Microstream Hub.
38+
- `serviceName`: Name of the service connecting to the hub.
39+
- `timeout`: Timeout for requests in milliseconds (default: 5000).
40+
- `heartbeatInterval`: Interval for sending heartbeats in milliseconds (default: 5000).
41+
- `logLevel`: Log level for the client (default: "info").
42+
43+
### Log Levels
44+
45+
- `debug`: Log everything (useful for development).
46+
- `info`: Log only important events (useful for production).
47+
- `warn`: Log only warnings and errors.
48+
- `error`: Log only errors.
49+
- `silent`: Disable all logs.

src/index.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { io, Socket } from "socket.io-client";
22
import { nanoid } from "nanoid";
3+
import Logger from "./utils/logger"; // Import the logger
34

45
/**
56
* Options for initializing the MicrostreamClient.
@@ -13,6 +14,8 @@ export interface MicrostreamClientOptions {
1314
timeout?: number;
1415
/** Interval for sending heartbeats in milliseconds (default: 5000). */
1516
heartbeatInterval?: number;
17+
/** Log level for the client (default: "info"). */
18+
logLevel?: "debug" | "info" | "warn" | "error" | "silent";
1619
}
1720

1821
/**
@@ -39,6 +42,7 @@ export class MicrostreamClient {
3942
private handlers: { [event: string]: (data: any) => any } = {};
4043
private pendingRequests: { [requestId: string]: (response: any) => void } =
4144
{};
45+
private logger: Logger; // Add logger instance
4246

4347
/**
4448
* Initializes a new MicrostreamClient.
@@ -49,29 +53,33 @@ export class MicrostreamClient {
4953
serviceName,
5054
timeout = 5000,
5155
heartbeatInterval = 5000,
56+
logLevel = "info", // Add logLevel option
5257
}: MicrostreamClientOptions) {
5358
this.serviceName = serviceName;
5459
this.timeout = timeout;
5560
this.heartbeatInterval = heartbeatInterval;
61+
this.logger = new Logger(logLevel); // Initialize logger
5662
this.socket = io(hubUrl, { query: { serviceName } });
5763

5864
// Handle connection
5965
this.socket.on("connect", () => {
60-
console.log(
66+
this.logger.info(
6167
`[${this.serviceName}] Connected to Microstream Hub at ${hubUrl}`
6268
);
6369
this.startHeartbeat();
6470
});
6571

6672
// Handle disconnection
6773
this.socket.on("disconnect", () => {
68-
console.log(`[${this.serviceName}] Disconnected from Microstream Hub`);
74+
this.logger.warn(
75+
`[${this.serviceName}] Disconnected from Microstream Hub`
76+
);
6977
this.stopHeartbeat();
7078
});
7179

7280
// Handle incoming requests
7381
this.socket.on("request", ({ id, event, data }) => {
74-
console.log(
82+
this.logger.debug(
7583
`[${this.serviceName}] Received request for event "${event}" (ID: ${id})`,
7684
data
7785
);
@@ -81,22 +89,22 @@ export class MicrostreamClient {
8189
try {
8290
// Execute the handler and get the response
8391
const response = this.handlers[event](data);
84-
console.log(
92+
this.logger.debug(
8593
`[${this.serviceName}] Sending response for event "${event}" (ID: ${id})`,
8694
response
8795
);
8896
// Send the response back to the requester
8997
this.socket.emit("response", { id, response });
9098
} catch (error) {
91-
console.error(
99+
this.logger.error(
92100
`[${this.serviceName}] Error handling request for event "${event}" (ID: ${id})`,
93101
error
94102
);
95103
// Handle any errors that occur during handler execution
96104
this.socket.emit("response", { id, error: "Internal server error" });
97105
}
98106
} else {
99-
console.warn(
107+
this.logger.warn(
100108
`[${this.serviceName}] No handler found for event "${event}" (ID: ${id})`
101109
);
102110
// No handler found for the event
@@ -106,15 +114,15 @@ export class MicrostreamClient {
106114

107115
// Handle responses to pending requests
108116
this.socket.on("response", ({ id, data }) => {
109-
console.log(
117+
this.logger.debug(
110118
`[${this.serviceName}] Received response for request ${id}`,
111119
data
112120
);
113121
if (this.pendingRequests[id]) {
114122
this.pendingRequests[id](data);
115123
delete this.pendingRequests[id];
116124
} else {
117-
console.warn(
125+
this.logger.warn(
118126
`[${this.serviceName}] Received unexpected response for request ${id}`,
119127
data
120128
);
@@ -177,23 +185,19 @@ export class MicrostreamClient {
177185

178186
private startHeartbeat() {
179187
if (this.heartbeatInterval > 0) {
180-
console.log(
188+
this.logger.info(
181189
`[${this.serviceName}] Starting heartbeat with interval ${this.heartbeatInterval}ms`
182190
);
183191
this.heartbeatTimer = setInterval(() => {
184-
/* console.log(
185-
`[${
186-
this.serviceName
187-
}] Sending heartbeat - ${new Date().toLocaleString()}`
188-
); */
192+
this.logger.debug(`[${this.serviceName}] Sending heartbeat}`);
189193
this.socket.emit("heartbeat", { serviceName: this.serviceName });
190194
}, this.heartbeatInterval);
191195
}
192196
}
193197

194198
private stopHeartbeat() {
195199
if (this.heartbeatTimer) {
196-
console.log(`[${this.serviceName}] Stopping heartbeat`);
200+
this.logger.info(`[${this.serviceName}] Stopping heartbeat`);
197201
clearInterval(this.heartbeatTimer);
198202
}
199203
}

src/utils/logger.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
export type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
2+
3+
export default class Logger {
4+
private logLevel: LogLevel;
5+
6+
constructor(logLevel: LogLevel = "info") {
7+
this.logLevel = logLevel;
8+
}
9+
10+
private shouldLog(level: LogLevel): boolean {
11+
const levels = ["debug", "info", "warn", "error", "silent"];
12+
return levels.indexOf(level) >= levels.indexOf(this.logLevel);
13+
}
14+
15+
private formatMessage(level: string, ...args: any[]): string {
16+
const timestamp = new Date().toISOString();
17+
return `[MicroStream Client][${timestamp}][${level.toUpperCase()}] ${args.join(
18+
" "
19+
)}`;
20+
}
21+
22+
debug(...args: any[]) {
23+
if (this.shouldLog("debug")) {
24+
console.debug(this.formatMessage("debug", ...args));
25+
}
26+
}
27+
28+
info(...args: any[]) {
29+
if (this.shouldLog("info")) {
30+
console.info(this.formatMessage("info", ...args));
31+
}
32+
}
33+
34+
warn(...args: any[]) {
35+
if (this.shouldLog("warn")) {
36+
console.warn(this.formatMessage("warn", ...args));
37+
}
38+
}
39+
40+
error(...args: any[]) {
41+
if (this.shouldLog("error")) {
42+
console.error(this.formatMessage("error", ...args));
43+
}
44+
}
45+
}

tsconfig.cjs.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
"declaration": true,
1010
"declarationMap": true
1111
},
12-
"include": ["src/**/*"]
12+
"include": ["src/**/*", "src/utils/**/*"] // Add this line
1313
}

tsconfig.esm.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
"declaration": true,
1010
"declarationMap": true
1111
},
12-
"include": ["src/**/*"]
12+
"include": ["src/**/*", "src/utils/**/*"] // Add this line
1313
}

0 commit comments

Comments
 (0)