Skip to content

Commit

Permalink
feat: add margin to logger messages with newline
Browse files Browse the repository at this point in the history
  • Loading branch information
asger-finding committed Aug 8, 2023
1 parent 7e8c23b commit 2857ac3
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/common/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,28 @@ const separator = process.platform === 'win32' ? '>' : '›';
const newTimestamp = (): string => new Date().toISOString()
.slice(11, -1);

const newlineSpacer = ' '.repeat(newTimestamp().length + separator.length + 2);

/**
* Takes in log arguments, finds strings
* and adds adequate spacing to newlines
* to stay inline with the first line with
* the timestamp.
*
* @param args Arguments passed to log function
* @returns Transformed argument list
*/
const transformArgs = (args: unknown[]): unknown[] => args.map(arg => (typeof arg === 'string'
? arg.replaceAll('\n', `\n${ newlineSpacer }`)
: arg));

/**
* If in development, log a timestamped message to the console in blue.
*
* @param args The arguments to log
*/
export const info = (...args: unknown[]): void => {
if (IS_DEVELOPMENT) console.log('\x1b[36m%s\x1b[0m', newTimestamp(), separator, ...args);
if (IS_DEVELOPMENT) console.log('\x1b[36m%s\x1b[0m', newTimestamp(), separator, ...transformArgs(args));
};

/**
Expand All @@ -26,7 +41,7 @@ export const info = (...args: unknown[]): void => {
* @param args The arguments to log
*/
export const warn = (...args: unknown[]): void => {
if (IS_DEVELOPMENT) console.warn('\x1b[33m%s\x1b[0m', newTimestamp(), separator, ...args);
if (IS_DEVELOPMENT) console.warn('\x1b[33m%s\x1b[0m', newTimestamp(), separator, ...transformArgs(args));
};

/**
Expand All @@ -35,5 +50,5 @@ export const warn = (...args: unknown[]): void => {
* @param args The arguments to log
*/
export const error = (...args: unknown[]): void => {
if (IS_DEVELOPMENT) console.error('\x1b[31m%s\x1b[0m', newTimestamp(), separator, ...args);
if (IS_DEVELOPMENT) console.error('\x1b[31m%s\x1b[0m', newTimestamp(), separator, ...transformArgs(args));
};

0 comments on commit 2857ac3

Please sign in to comment.