Skip to content

Commit

Permalink
Stringify non-string logging
Browse files Browse the repository at this point in the history
  • Loading branch information
mattwebbio committed Oct 1, 2022
1 parent 6cd5a32 commit 21737a9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
13 changes: 13 additions & 0 deletions src/log.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe('Log', () => {

afterEach(() => {
jest.resetModules();
jest.restoreAllMocks();
});

afterAll(() => {
Expand All @@ -27,6 +28,18 @@ describe('Log', () => {
`${chalk.dim('8/27/2022, 8:17:31 AM')}: Hello world`
);
});

test('should log stringified', () => {
const consoleLog = jest.spyOn(console, 'log');

Log.info({ foo: 'bar' });

expect(consoleLog).toHaveBeenCalledTimes(1);
expect(consoleLog).toHaveBeenCalledWith(
// eslint-disable-next-line no-useless-escape
`${chalk.dim('8/27/2022, 8:17:31 AM')}: {\"foo\":\"bar\"}`
);
});
});

describe('verbose', () => {
Expand Down
11 changes: 8 additions & 3 deletions src/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ import { Config } from './config.js';

export class Log {
static info(message: unknown) {
console.log(`${this.timestamp}: ${message}`);
console.log(`${this.timestamp}: ${this.stringify(message)}`);
}

static verbose(message: unknown) {
if (Config.verboseMode && message) this.info(message);
if (Config.verboseMode && message) this.info(this.stringify(message));
}

static error(message: unknown) {
console.error(`${this.timestamp}: ${chalk.red(message)}`);
console.error(`${this.timestamp}: ${chalk.red(this.stringify(message))}`);
}

private static stringify(message: unknown): string {
if (typeof message === 'string') return message;
else return JSON.stringify(message);
}

private static get timestamp(): string {
Expand Down

0 comments on commit 21737a9

Please sign in to comment.