feat(common): add log filtering function

This commit is contained in:
Julien Barbay
2025-03-18 10:15:04 +07:00
parent 86eb46d66d
commit a191c1f905
2 changed files with 85 additions and 2 deletions

View File

@@ -3,10 +3,51 @@ import { isObject } from '../utils/shared.utils';
import { ConsoleLogger } from './console-logger.service';
import { isLogLevelEnabled } from './utils';
const LOG_LEVELS = [
'verbose',
'debug',
'log',
'warn',
'error',
'fatal',
] as const satisfies string[];
/**
* @publicApi
*/
export type LogLevel = 'log' | 'error' | 'warn' | 'debug' | 'verbose' | 'fatal';
export type LogLevel = (typeof LOG_LEVELS)[number];
/**
* @publicApi
*/
export function isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel {
return LOG_LEVELS.includes(maybeLogLevel);
}
/**
* @publicApi
*/
export function filterLogLevels(parseableString = ''): LogLevel[] {
const sanitizedSring = parseableString.replaceAll(' ', '').toLowerCase();
if (sanitizedSring[0] === '>') {
const orEqual = sanitizedSring[1] === '=';
const logLevelIndex = (LOG_LEVELS as string[]).indexOf(
sanitizedSring.substring(orEqual ? 2 : 1),
);
if (logLevelIndex === -1) {
throw new Error(`parse error (unknown log level): ${sanitizedSring}`);
}
return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
} else if (sanitizedSring.includes(',')) {
return sanitizedSring.split(',').filter(isLogLevel);
}
return isLogLevel(sanitizedSring) ? [sanitizedSring] : LOG_LEVELS;
}
/**
* @publicApi

View File

@@ -1,9 +1,51 @@
import { expect } from 'chai';
import 'reflect-metadata';
import * as sinon from 'sinon';
import { ConsoleLogger, Logger, LoggerService, LogLevel } from '../../services';
import {
ConsoleLogger,
filterLogLevels,
Logger,
LoggerService,
LogLevel,
} from '../../services';
describe('Logger', () => {
describe('[log helpers]', () => {
describe('when using filterLogLevels', () => {
it('should correctly parse an exclusive range', () => {
const returned = filterLogLevels('>warn');
expect(returned).toEqual(['error', 'fatal']);
});
it('should correctly parse an inclusive range', () => {
const returned = filterLogLevels('>=warn');
expect(returned).toEqual(['warn', 'error', 'fatal']);
});
it('should correctly parse a string list', () => {
const returned = filterLogLevels('verbose,warn,fatal');
expect(returned).toEqual(['verbose', 'warn', 'fatal']);
});
it('should correctly parse a single log level', () => {
const returned = filterLogLevels('debug');
expect(returned).toEqual(['debug']);
});
it('should return all otherwise', () => {
const returned = filterLogLevels();
expect(returned).toEqual([
'verbose',
'debug',
'log',
'warn',
'error',
'fatal',
]);
});
});
});
describe('[static methods]', () => {
describe('when the default logger is used', () => {
let processStdoutWriteSpy: sinon.SinonSpy;