Skip to content

Commit

Permalink
fix: fix incorrect logger setup when introducing environmental variables
Browse files Browse the repository at this point in the history
  • Loading branch information
Howard86 committed Nov 25, 2022
1 parent d237e3c commit ed9068f
Showing 1 changed file with 20 additions and 20 deletions.
40 changes: 20 additions & 20 deletions src/lib/api-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ enum LoggerLevelMap {
info,
warn,
error,
silent,
}

export type LoggerLevel = keyof typeof LoggerLevelMap;

const DEFAULT_LOGGER_LEVEL: LoggerLevel =
process.env.NODE_ENV === 'development' ? 'info' : 'error';
const DEFAULT_CONTEXT = '[next-api-handler]';

export interface DefaultApiLoggerOption {
Expand All @@ -27,32 +26,33 @@ export interface DefaultApiLoggerOption {

export class DefaultApiLogger implements ApiLogger {
private readonly context: string;
private readonly level: number;
private readonly DEFAULT_MESSAGE = '';

constructor({
context = DEFAULT_CONTEXT,
loggerLevel = DEFAULT_LOGGER_LEVEL,
}: DefaultApiLoggerOption = {}) {
this.context = context;
this.level = LoggerLevelMap[loggerLevel];
private readonly level: LoggerLevel;

constructor(option: DefaultApiLoggerOption = {}) {
this.context = option.context || DEFAULT_CONTEXT;
this.level = option.loggerLevel || this.defaultLoggerLevel;
}

debug = this.logMessage('debug');
info = this.logMessage('info');
warn = this.logMessage('warn');
error = this.logMessage('error');

private logMessage(level: LoggerLevel) {
if (this.level > LoggerLevelMap[level]) return this.emptyFunction;
private get defaultLoggerLevel(): LoggerLevel {
return process.env.NODE_ENV === 'test'
? 'silent'
: process.env.NODE_ENV === 'development'
? 'info'
: 'error';
}

return (message = this.DEFAULT_MESSAGE) => {
console[level](
`${this.context} ${level} ${new Date().toISOString()} ${message}`
);
private logMessage(level: Exclude<LoggerLevel, 'silent'>) {
return (message?: string) => {
if (LoggerLevelMap[this.level] <= LoggerLevelMap[level]) {
console[level](
`${this.context} ${level} ${new Date().toISOString()} ${message}`
);
}
};
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
private emptyFunction(_message?: string) {}
}

0 comments on commit ed9068f

Please sign in to comment.