Skip to content

Commit

Permalink
Updated AcquireLogger to support timezone for logging time stamps
Browse files Browse the repository at this point in the history
  • Loading branch information
Erik Lysne committed Jul 11, 2023
1 parent ac678ab commit 3cc17dd
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 23 deletions.
46 changes: 41 additions & 5 deletions packages/core/src/classes/AcquireLogger.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,26 @@ import { LogLevel, Logger, LoggerFn } from "@/interfaces/Logger.interface";

export type AcquireLogColor = keyof typeof AcquireLogger.color;

export interface AcquireLoggerOptions {
logFn?: LoggerFn;
logLevels?: LogLevel[] | "all";
timezone?: string;
}

export default class AcquireLogger implements Logger {
constructor(
private logFn: LoggerFn = console.log,
private logLevels: LogLevel[] | "all" = "all"
) {
private logFn: LoggerFn;
private logLevels: LogLevel[] | "all";
private timezone: string;

constructor(options?: AcquireLoggerOptions) {
const {
logFn = console.log,
logLevels = "all",
timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
} = options ?? {};
this.logFn = logFn;
this.logLevels = logLevels;
this.timezone = timezone;
}

static color = {
Expand Down Expand Up @@ -64,6 +77,29 @@ export default class AcquireLogger implements Logger {
return `${AcquireLogger.style.bold}${text}${AcquireLogger.style.reset}`;
}

private now(): Date {
const date = new Date();

const dateTimeFormat = new Intl.DateTimeFormat("en-US", {
timeZone: this.timezone,
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
const parts = dateTimeFormat.formatToParts(date);

const hours = parts.find((part) => part.type === "hour")?.value;
const minutes = parts.find((part) => part.type === "minute")?.value;
const seconds = parts.find((part) => part.type === "second")?.value;

date.setHours(parseInt(hours || "0"));
date.setMinutes(parseInt(minutes || "0"));
date.setSeconds(parseInt(seconds || "0"));

return date;
}

private makeLog(
level: LogLevel,
color: AcquireLogColor,
Expand All @@ -78,7 +114,7 @@ export default class AcquireLogger implements Logger {
return value.toString().padStart(2, "0");
}

const timestamp = new Date();
const timestamp = this.now();
const timestampPrefix = AcquireLogger.colorize(
`${zeroPad(timestamp.getDate())}/${zeroPad(
timestamp.getMonth() + 1
Expand Down
18 changes: 10 additions & 8 deletions packages/core/src/middleware/AcquireRequestLogger.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
import AcquireLogger, { AcquireLogColor } from "@/classes/AcquireLogger.class";
import AcquireLogger, {
AcquireLogColor,
AcquireLoggerOptions
} from "@/classes/AcquireLogger.class";
import RequestMethod from "@/constants/RequestMethod.const";
import { AcquireContext } from "@/interfaces/AcquireContext.interface";
import {
AcquireMiddlewareClass,
AcquireMiddlewareFn
} from "@/interfaces/AcquireMiddleware.interface";
import { LogLevel, LoggerFn } from "@/interfaces/Logger.interface";
import axios from "axios";

export interface AcquireRequestLoggerOptions {
logFn?: LoggerFn;
logLevels?: LogLevel[] | "all";
export interface AcquireRequestLoggerOptions extends AcquireLoggerOptions {
order?: number;
}

export default class AcquireRequestLogger implements AcquireMiddlewareClass {
public order = 1000;
public order;

private logger: AcquireLogger;

constructor(options?: AcquireRequestLoggerOptions) {
const { logFn, logLevels } = options ?? {};
this.logger = new AcquireLogger(logFn, logLevels);
const { order = 1000, ...rest } = options ?? {};
this.logger = new AcquireLogger(rest);
this.order = order;
}

getStatusCodeColor(statusCode: number): AcquireLogColor {
Expand Down
9 changes: 5 additions & 4 deletions packages/core/tests/classes/AcquireLogger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ describe("class: AcquireLogger", () => {
const { blue, red, brightBlack, reset } = AcquireLogger.color;
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});

const logger = new AcquireLogger();
const logger = new AcquireLogger({ timezone: "UTC" });

const OriginalDate = global.Date;

beforeAll(() => {
const mockDate = new OriginalDate("2023-07-03T11:22:33Z");

function MockDate(): Date {
return mockDate;
return new OriginalDate(mockDate.getTime());
}

MockDate.UTC = OriginalDate.UTC;
MockDate.parse = OriginalDate.parse;
MockDate.now = (): number => mockDate.getTime();
Expand Down Expand Up @@ -44,15 +45,15 @@ describe("class: AcquireLogger", () => {
logger.info("Hello world");

expect(consoleSpy).toHaveBeenCalledWith(
`${reset}${blue}[Acquire]${reset} - ${brightBlack}03/07/2023 13:22:33${reset} - Hello world`
`${reset}${blue}[Acquire]${reset} - ${brightBlack}03/07/2023 11:22:33${reset} - Hello world`
);
});

it("should have the correct formatting for logging error", () => {
logger.error("Hello world");

expect(consoleSpy).toHaveBeenCalledWith(
`${reset}${red}[Acquire]${reset} - ${brightBlack}03/07/2023 13:22:33${reset} - Hello world`
`${reset}${red}[Acquire]${reset} - ${brightBlack}03/07/2023 11:22:33${reset} - Hello world`
);
});
});
Expand Down
21 changes: 15 additions & 6 deletions packages/core/tests/middleware/AcquireRequestLogger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,21 @@ describe("middleware: AcquireRequestLogger", () => {

const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
const acquire = new Acquire(axiosInstance);
acquire.use(new AcquireRequestLogger());
acquire.use(
new AcquireRequestLogger({
timezone: "UTC"
})
);

const OriginalDate = global.Date;

beforeAll(() => {
const mockDate = new OriginalDate("2023-07-03T11:22:33Z");

function MockDate(): Date {
return mockDate;
return new OriginalDate(mockDate.getTime());
}

MockDate.UTC = OriginalDate.UTC;
MockDate.parse = OriginalDate.parse;
MockDate.now = (): number => mockDate.getTime();
Expand All @@ -30,6 +35,10 @@ describe("middleware: AcquireRequestLogger", () => {
global.Date = MockDate as any;
});

afterAll(() => {
global.Date = OriginalDate;
});

afterEach(() => {
consoleSpy.mockRestore();
mockAxios.reset();
Expand All @@ -47,7 +56,7 @@ describe("middleware: AcquireRequestLogger", () => {
await getUsers();

expect(consoleSpy).toHaveBeenCalledWith(
`${reset}${blue}[Acquire]${reset} - ${brightBlack}03/07/2023 13:22:33${reset} - ${green} [Executed]${reset} ${cyan}[GET: /users]:${reset} ${green}200${reset}`
`${reset}${blue}[Acquire]${reset} - ${brightBlack}03/07/2023 11:22:33${reset} - ${green} [Executed]${reset} ${cyan}[GET: /users]:${reset} ${green}200${reset}`
);
});

Expand All @@ -63,7 +72,7 @@ describe("middleware: AcquireRequestLogger", () => {
await expect(getUsers()).rejects.toThrow();

expect(consoleSpy).toHaveBeenCalledWith(
`${reset}${red}[Acquire]${reset} - ${brightBlack}03/07/2023 13:22:33${reset} - ${green} [Executed]${reset} ${cyan}[GET: /users]:${reset} ${red}404 - Request failed with status code 404${reset}`
`${reset}${red}[Acquire]${reset} - ${brightBlack}03/07/2023 11:22:33${reset} - ${green} [Executed]${reset} ${cyan}[GET: /users]:${reset} ${red}404 - Request failed with status code 404${reset}`
);
});

Expand All @@ -77,7 +86,7 @@ describe("middleware: AcquireRequestLogger", () => {
await getUsers.mock();

expect(consoleSpy).toHaveBeenCalledWith(
`${reset}${blue}[Acquire]${reset} - ${brightBlack}03/07/2023 13:22:33${reset} - ${yellow}[Mocked ->${brightBlue}on demand${yellow}]${reset} ${cyan}[GET: /users]:${reset} ${green}200 - OK${reset}`
`${reset}${blue}[Acquire]${reset} - ${brightBlack}03/07/2023 11:22:33${reset} - ${yellow}[Mocked ->${brightBlue}on demand${yellow}]${reset} ${cyan}[GET: /users]:${reset} ${green}200 - OK${reset}`
);
});

Expand All @@ -102,7 +111,7 @@ describe("middleware: AcquireRequestLogger", () => {
await expect(getUsers.mock()).rejects.toThrow();

expect(consoleSpy).toHaveBeenCalledWith(
`${reset}${red}[Acquire]${reset} - ${brightBlack}03/07/2023 13:22:33${reset} - ${yellow}[Mocked ->${green}intercepted${yellow}]${reset} ${cyan}[GET: /users]:${reset} ${red}404 - Not found${reset}`
`${reset}${red}[Acquire]${reset} - ${brightBlack}03/07/2023 11:22:33${reset} - ${yellow}[Mocked ->${green}intercepted${yellow}]${reset} ${cyan}[GET: /users]:${reset} ${red}404 - Not found${reset}`
);
});
});

0 comments on commit 3cc17dd

Please sign in to comment.