Skip to content

Commit

Permalink
perf(common): faster date format function using intl
Browse files Browse the repository at this point in the history
  • Loading branch information
H4ad committed Jan 8, 2023
1 parent dc5bd80 commit 65e8704
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 24 deletions.
22 changes: 10 additions & 12 deletions packages/common/services/console-logger.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ const DEFAULT_LOG_LEVELS: LogLevel[] = [
'verbose',
];

const dateTimeFormatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
day: '2-digit',
month: '2-digit',
});

@Injectable()
export class ConsoleLogger implements LoggerService {
private static lastTimestampAt?: number;
Expand Down Expand Up @@ -162,18 +171,7 @@ export class ConsoleLogger implements LoggerService {
}

protected getTimestamp(): string {
const localeStringOptions = {
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
day: '2-digit',
month: '2-digit',
};
return new Date(Date.now()).toLocaleString(
undefined,
localeStringOptions as Intl.DateTimeFormatOptions,
);
return dateTimeFormatter.format(Date.now());
}

protected printMessages(
Expand Down
22 changes: 10 additions & 12 deletions packages/common/services/logger.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ interface LogBufferRecord {

const DEFAULT_LOGGER = new ConsoleLogger();

const dateTimeFormatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
day: '2-digit',
month: '2-digit',
});

@Injectable()
export class Logger implements LoggerService {
protected static logBuffer = new Array<LogBufferRecord>();
Expand Down Expand Up @@ -249,18 +258,7 @@ export class Logger implements LoggerService {
}

static getTimestamp() {
const localeStringOptions = {
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
day: '2-digit',
month: '2-digit',
};
return new Date(Date.now()).toLocaleString(
undefined,
localeStringOptions as Intl.DateTimeFormatOptions,
);
return dateTimeFormatter.format(Date.now());
}

static overrideLogger(logger: LoggerService | LogLevel[] | boolean) {
Expand Down

0 comments on commit 65e8704

Please sign in to comment.