Skip to content

Commit

Permalink
chore: Simplify logger service
Browse files Browse the repository at this point in the history
  • Loading branch information
neet committed Nov 2, 2023
1 parent 8cb9599 commit 3cedcf8
Show file tree
Hide file tree
Showing 13 changed files with 36 additions and 193 deletions.
4 changes: 2 additions & 2 deletions src/__mocks__/logger-mock-impl.ts
@@ -1,7 +1,7 @@
import { BaseLogger } from '../adapters/logger';
import { Logger } from "../interfaces";

export const log = jest.fn();

export class LoggerMockImpl extends BaseLogger {
export class LoggerMockImpl implements Logger {
log = log;
}
3 changes: 2 additions & 1 deletion src/adapters/clients.ts
@@ -1,3 +1,4 @@
import { type LogType } from "../interfaces";
import { type mastodon } from "../mastodon";
import {
createActionProxy,
Expand All @@ -11,7 +12,7 @@ import {
type WebSocketConfigProps,
} from "./config";
import { HttpNativeImpl } from "./http";
import { createLogger, type LogType } from "./logger";
import { createLogger } from "./logger";

Check warning on line 15 in src/adapters/clients.ts

View check run for this annotation

Codecov / codecov/patch

src/adapters/clients.ts#L15

Added line #L15 was not covered by tests
import { SerializerNativeImpl } from "./serializers";
import { WebSocketConnectorImpl } from "./ws";

Expand Down
10 changes: 5 additions & 5 deletions src/adapters/http/http-native-impl.ts
Expand Up @@ -28,8 +28,8 @@ export class HttpNativeImpl extends BaseHttp implements Http {
const request = this.createRequest(params);

try {
this.logger?.info(`↑ ${request.method} ${request.url}`);
this.logger?.debug("\tbody", {
this.logger?.log("info", `↑ ${request.method} ${request.url}`);
this.logger?.log("debug", "\tbody", {
encoding: params.encoding,
body: params.body,
});
Expand All @@ -47,15 +47,15 @@ export class HttpNativeImpl extends BaseHttp implements Http {
}

const data = this.serializer.deserialize(encoding, text);
this.logger?.info(`↓ ${request.method} ${request.url}`);
this.logger?.debug("\tbody", text);
this.logger?.log("info", `↓ ${request.method} ${request.url}`);
this.logger?.log("debug", "\tbody", text);

return {
headers: response.headers,
data,
};
} catch (error) {
this.logger?.debug(`HTTP failed`, error);
this.logger?.log("debug", `HTTP failed`, error);
throw await this.createError(error);
}
}
Expand Down
131 changes: 0 additions & 131 deletions src/adapters/logger/base-logger.spec.ts

This file was deleted.

31 changes: 0 additions & 31 deletions src/adapters/logger/base-logger.ts

This file was deleted.

3 changes: 2 additions & 1 deletion src/adapters/logger/factory.ts
@@ -1,4 +1,5 @@
import { LogLevel, type LogType } from "./log-level";
import { type LogType } from "../../interfaces";
import { LogLevel } from "./log-level";
import { LoggerConsoleImpl } from "./logger-console-impl";

export const createLogger = (type?: LogType): LoggerConsoleImpl => {
Expand Down
1 change: 0 additions & 1 deletion src/adapters/logger/index.ts
@@ -1,4 +1,3 @@
export * from "./base-logger";
export * from "./logger-console-impl";
export * from "./log-level";
export * from "./factory";
4 changes: 2 additions & 2 deletions src/adapters/logger/log-level.ts
@@ -1,3 +1,5 @@
import { type LogType } from "../../interfaces";

/* eslint-disable unicorn/prefer-math-trunc */
const LOG_TYPES = Object.freeze({
DEBUG: 1 << 0,
Expand All @@ -6,8 +8,6 @@ const LOG_TYPES = Object.freeze({
ERROR: 1 << 3,
});

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

export class LogLevel {
private constructor(private readonly level: number) {}

Expand Down
8 changes: 4 additions & 4 deletions src/adapters/logger/logger-console-impl.spec.ts
Expand Up @@ -9,28 +9,28 @@ describe("LoggerConsoleImpl", () => {
it("logs debug", () => {
const consoleDebug = jest.spyOn(console, "debug").mockImplementation();
const logger = new LoggerConsoleImpl(LogLevel.from("debug"));
logger.debug("message", { meta: "meta" });
logger.log("debug", "message", { meta: "meta" });
expect(consoleDebug).toHaveBeenCalledWith("message", { meta: "meta" });
});

it("logs info", () => {
const consoleInfo = jest.spyOn(console, "info").mockImplementation();
const logger = new LoggerConsoleImpl(LogLevel.from("info"));
logger.info("message", { meta: "meta" });
logger.log("info", "message", { meta: "meta" });
expect(consoleInfo).toHaveBeenCalledWith("message", { meta: "meta" });
});

it("logs warn", () => {
const consoleWarn = jest.spyOn(console, "warn").mockImplementation();
const logger = new LoggerConsoleImpl(LogLevel.from("warn"));
logger.warn("message", { meta: "meta" });
logger.log("warn", "message", { meta: "meta" });
expect(consoleWarn).toHaveBeenCalledWith("message", { meta: "meta" });
});

it("logs error", () => {
const consoleError = jest.spyOn(console, "error").mockImplementation();
const logger = new LoggerConsoleImpl(LogLevel.from("error"));
logger.error("message", { meta: "meta" });
logger.log("error", "message", { meta: "meta" });
expect(consoleError).toHaveBeenCalledWith("message", { meta: "meta" });
});
});
13 changes: 9 additions & 4 deletions src/adapters/logger/logger-console-impl.ts
@@ -1,10 +1,15 @@
/* eslint-disable no-console */
import { type Logger } from "../../interfaces";
import { BaseLogger } from "./base-logger";
import { type LogType } from "./log-level";
import { type Logger, type LogType } from "../../interfaces";
import { type LogLevel } from "./log-level";

export class LoggerConsoleImpl implements Logger {
constructor(private readonly level: LogLevel) {}

export class LoggerConsoleImpl extends BaseLogger implements Logger {
log(type: LogType, message: string, meta: unknown): void {
if (!this.level.satisfies(type)) {
return;
}

const args = meta == undefined ? [message] : [message, meta];
switch (type) {
case "debug": {
Expand Down
8 changes: 4 additions & 4 deletions src/adapters/ws/web-socket-connector.ts
Expand Up @@ -72,26 +72,26 @@ export class WebSocketConnectorImpl implements WebSocketConnector {
this.ws?.close();

try {
this.logger?.info("Connecting to WebSocket...");
this.logger?.log("info", "Connecting to WebSocket...");
{
const ctor = (this.props.implementation ??
WebSocket) as typeof WebSocket;
const ws = new ctor(...this.props.constructorParameters);
await waitForOpen(ws);
this.ws = ws;
}
this.logger?.info("Connected to WebSocket");
this.logger?.log("info", "Connected to WebSocket");

for (const { resolve } of this.queue) {
resolve(this.ws);
}
this.queue = [];

await waitForClose(this.ws);
this.logger?.info("WebSocket closed");
this.logger?.log("info", "WebSocket closed");
this.backoff.clear();
} catch (error) {
this.logger?.error("WebSocket error:", error);
this.logger?.log("error", "WebSocket error:", error);
}

if (this.disableRetry) {
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/ws/web-socket-subscription.ts
Expand Up @@ -21,7 +21,7 @@ export class WebSocketSubscription implements mastodon.streaming.Subscription {
) {}

async *values(): AsyncIterableIterator<mastodon.streaming.Event> {
this.logger?.info("Subscribing to stream", this.stream);
this.logger?.log("info", "Subscribing to stream", this.stream);

while (this.connector.canAcquire()) {
this.connection = await this.connector.acquire();
Expand All @@ -34,12 +34,12 @@ export class WebSocketSubscription implements mastodon.streaming.Subscription {
...this.params,
});

this.logger?.debug("↑ WEBSOCKET", data);
this.logger?.log("debug", "↑ WEBSOCKET", data);
this.connection.send(data);

for await (const event of this.transformIntoEvents(messages)) {
if (!this.matches(event)) continue;
this.logger?.debug("↓ WEBSOCKET", event);
this.logger?.log("debug", "↓ WEBSOCKET", event);
yield event;
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/interfaces/logger.ts
@@ -1,6 +1,5 @@
export type LogType = "debug" | "info" | "warn" | "error";

export interface Logger {
debug(message: string, meta?: unknown): void;
info(message: string, meta?: unknown): void;
warn(message: string, meta?: unknown): void;
error(message: string, meta?: unknown): void;
log(type: LogType, message: string, meta?: unknown): void;
}

0 comments on commit 3cedcf8

Please sign in to comment.