Skip to content

Commit

Permalink
refactor: extract colorize
Browse files Browse the repository at this point in the history
  • Loading branch information
Zlatin Stanimirov committed Mar 11, 2022
1 parent 89d9765 commit 674a09c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 18 deletions.
39 changes: 25 additions & 14 deletions packages/common/services/console-logger.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,26 +183,17 @@ export class ConsoleLogger implements LoggerService {
logLevel: LogLevel = 'log',
writeStreamType?: 'stdout' | 'stderr',
) {
const color = this.getColorByLogLevel(logLevel);
messages.forEach(message => {
const output = isPlainObject(message)
? `${color('Object:')}\n${JSON.stringify(
message,
(key, value) =>
typeof value === 'bigint' ? value.toString() : value,
2,
)}\n`
: color(message as string);

const pidMessage = color(`[Nest] ${process.pid} - `);
const pidMessage = `[Nest] ${process.pid} - `;
const contextMessage = context ? yellow(`[${context}] `) : '';
const timestampDiff = this.updateAndGetTimestampDiff();
const formattedLogLevel = color(logLevel.toUpperCase().padStart(7, ' '));
const formattedLogLevel = logLevel.toUpperCase().padStart(7, ' ');
const formatedMessage = this.formatMessage(
logLevel,
message,
pidMessage,
formattedLogLevel,
contextMessage,
output,
timestampDiff,
);

Expand All @@ -211,15 +202,35 @@ export class ConsoleLogger implements LoggerService {
}

protected formatMessage(
logLevel: LogLevel,
message: unknown,
pidMessage: string,
formattedLogLevel: string,
contextMessage: string,
output: string,
timestampDiff: string,
) {
const output = this.stringifyMessage(message, logLevel);
pidMessage = this.colorize(pidMessage, logLevel);
formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
return `${pidMessage}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}\n`;
}

protected stringifyMessage(message: unknown, logLevel: LogLevel) {
return isPlainObject(message)
? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(
message,
(key, value) =>
typeof value === 'bigint' ? value.toString() : value,
2,
)}\n`
: this.colorize(message as string, logLevel);
}

protected colorize(message: string, logLevel: LogLevel) {
const color = this.getColorByLogLevel(logLevel);
return color(message);
}

protected printStackTrace(stack: string) {
if (!stack) {
return;
Expand Down
37 changes: 33 additions & 4 deletions packages/common/test/services/logger.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect } from 'chai';
import 'reflect-metadata';
import * as sinon from 'sinon';
import { ConsoleLogger, Logger, LoggerService } from '../../services';
import { ConsoleLogger, Logger, LoggerService, LogLevel } from '../../services';

describe('Logger', () => {
describe('[static methods]', () => {
Expand Down Expand Up @@ -526,25 +526,54 @@ describe('Logger', () => {
beforeEach(() => {
processStdoutWriteSpy = sinon.spy(process.stdout, 'write');
});
afterEach(() => {
processStdoutWriteSpy.restore();
});

it('should support custom formatter', () => {
class CustomConsoleLogger extends ConsoleLogger {
protected formatMessage(
logLevel: LogLevel,
message: unknown,
pidMessage: string,
formattedLogLevel: string,
contextMessage: string,
timestampDiff: string,
) {
return `Prefix: ${message}`;
}
}

const consoleLogger = new CustomConsoleLogger();
consoleLogger.debug('test');

expect(processStdoutWriteSpy.firstCall.firstArg).to.equal(`Prefix: test`);
});

it('should support custom formatter and colorizer', () => {
class CustomConsoleLogger extends ConsoleLogger {
protected formatMessage(
logLevel: LogLevel,
message: unknown,
pidMessage: string,
formattedLogLevel: string,
contextMessage: string,
output: string,
timestampDiff: string,
) {
return `Prefix: ${output}`;
const strMessage = this.stringifyMessage(message, logLevel);
return `Prefix: ${strMessage}`;
}

protected colorize(message: string, logLevel: LogLevel): string {
return `~~~${message}~~~`;
}
}

const consoleLogger = new CustomConsoleLogger();
consoleLogger.debug('test');

expect(processStdoutWriteSpy.firstCall.firstArg).to.equal(
`Prefix: \u001b[95mtest\u001b[39m`,
`Prefix: ~~~test~~~`,
);
});
});
Expand Down

0 comments on commit 674a09c

Please sign in to comment.