Skip to content

Commit

Permalink
Add printLogLevel option (#7)
Browse files Browse the repository at this point in the history
* Add `timeStart` function

* Support numeric loglevel

* Add printLogLevel option
  • Loading branch information
TwitchBronBron authored Apr 25, 2024
1 parent be727f4 commit b357f64
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 10 deletions.
33 changes: 33 additions & 0 deletions src/Logger.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,22 @@ describe('Logger', () => {
)
).to.eql(`[${timestamp}][ERROR] hello world`);
});

it('excludes logLevel when printLogLevel is false', () => {
logger.printLogLevel = false;
expect(
logger.formatMessage(
logger.buildLogMessage('error', 'hello world'),
false
)
).to.eql(`[${timestamp}] hello world`);
});
});

it('logLevelColorWrap defaults to logLevel', () => {
expect(
logger['logLevelColorWrap']('[LOG]', 'log')
).to.eql(`[LOG]`);
});

describe('timeStart', () => {
Expand All @@ -536,6 +552,23 @@ describe('Logger', () => {
['info', 'message', `finished. (10ms)`]
]);
});

it('honors the color setting', async () => {
chalk.level = 3;
sinon.stub(Stopwatch.prototype, 'getDurationText').callsFake(() => '10ms');
const stub = sinon.stub(logger, 'write').callThrough();
logger.logLevel = 'info';
logger.enableColor = true;
const stop = logger.timeStart('info', 'message');
await sleep(10);
stop();
expect(
stub.getCalls().map(x => x.args)
).to.eql([
['info', 'message'],
['info', 'message', `finished. (${chalk.blue('10ms')})`]
]);
});
});

describe('time', () => {
Expand Down
57 changes: 47 additions & 10 deletions src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,29 @@ export class Logger {
this.options.enableColor = value;
}

/**
* Get colored text if color is enabled, or the raw text back if color is not enabled
*/
private colorWrap(text: string, color: keyof typeof chalk, enableColor = this.enableColor) {
if (enableColor) {
return (chalk[color] as any)(text);
} else {
return text;
}
}

/**
* Wrap the text in the color of the given logLevel
*/
private logLevelColorWrap(text: string, logLevel: LogLevel, enableColor = this.enableColor) {
if (enableColor) {
const logColorFn = LogLevelColor[logLevel] ?? LogLevelColor.log;
return logColorFn(text);
} else {
return text;
}
}

/**
* Should the log level be padded with trailing spaces when printed
*/
Expand All @@ -102,6 +125,16 @@ export class Logger {
this.options.consistentLogLevelWidth = value;
}

/**
* Should the log level be padded with trailing spaces when printed
*/
public get printLogLevel(): boolean {
return this.options.printLogLevel ?? this.options.parent?.printLogLevel ?? true;
}
public set printLogLevel(value: boolean) {
this.options.printLogLevel = value;
}

/**
* Get notified about every log message
* @param subscriber a function that is called with the given log message
Expand Down Expand Up @@ -206,13 +239,11 @@ export class Logger {
if (this.consistentLogLevelWidth) {
logLevelText = logLevelText.padEnd(5, ' ');
}
if (enableColor) {
timestampText = chalk.grey(timestampText);
const logColorFn = LogLevelColor[message.logLevel] ?? LogLevelColor.log;
logLevelText = logColorFn(logLevelText);
}

let result = timestampText + '[' + logLevelText + ']';
let result = this.colorWrap(timestampText, 'grey', enableColor);
if (this.printLogLevel) {
result += '[' + this.logLevelColorWrap(logLevelText, message.logLevel, enableColor) + ']';
}

const prefix = message.prefixes.join('');
if (prefix.length > 0) {
Expand Down Expand Up @@ -306,7 +337,7 @@ export class Logger {

return (status = 'finished') => {
stopwatch.stop();
this.write(logLevel, ...messages, `${status}. (${chalk.blue(stopwatch.getDurationText())})`);
this.write(logLevel, ...messages, `${status}. (${this.colorWrap(stopwatch.getDurationText(), 'blue')})`);
};
}
return noop;
Expand All @@ -323,9 +354,10 @@ export class Logger {
//call the log if loglevel is in range
if (this.isLogLevelEnabled(logLevel)) {
const stopwatch = new Stopwatch();
messages = Array.isArray(messages) ? messages : [messages];

//write the initial log
this.write(logLevel, Array.isArray(messages) ? messages : [messages]);
this.write(logLevel, ...messages as unknown[]);

stopwatch.start();
//execute the action
Expand All @@ -334,7 +366,7 @@ export class Logger {
//return a function to call when the timer is complete
const done = () => {
stopwatch.stop();
this.write(logLevel, [...messages, `finished. (${chalk.blue(stopwatch.getDurationText())})`]);
this.write(logLevel, ...messages as unknown[], `finished. (${this.colorWrap(stopwatch.getDurationText(), 'blue')})`);
};

//if this is a promise, wait for it to resolve and then return the original result
Expand Down Expand Up @@ -451,13 +483,18 @@ export interface LoggerOptions {
*/
parent?: Logger;
/**
* If true, colors will be used in transports that support it.
* If true, colors will be used in transports that support it. If the console you're using doesn't support colors, then colors will still be disabled.
* This is a way to disable colors globally in situations when color IS supported.
*/
enableColor?: boolean;
/**
* Should the log level be padded with trailing spaces when printed
*/
consistentLogLevelWidth?: boolean;
/**
* Should the log level be printed in the log message
*/
printLogLevel?: boolean;
}

export interface LogMessage {
Expand Down

0 comments on commit b357f64

Please sign in to comment.