Skip to content

Commit

Permalink
Introduce basic pre/post processor logic (#96)
Browse files Browse the repository at this point in the history
* Intorduce pro/post processors

* Implement tests

* Fix lint

* Fix test coverage and remove method scope processors

* Fix generics

* More options for processors

* JsDocs
  • Loading branch information
Antony1060 authored Feb 16, 2022
1 parent c2a4707 commit fd9f1ef
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 9 deletions.
41 changes: 35 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export type SharedConfig = {
paddingChar?: string;
};

export type LogConfig = SharedConfig & {
export type LogConfig<M extends string> = SharedConfig & {
/**
* Wether to add spacing in front or behind the specified label
* @default "PREPEND"
Expand All @@ -72,6 +72,20 @@ export type LogConfig = SharedConfig & {
* @example ['error', 'important', 'success'] (only logs error, important, and success)
*/
filter: RuntimeOrValue<string[] | undefined>;

/**
* A list of functions to handle input pre processing
* @default []
* @example [(in) => in]
*/
preProcessors?: ((input: LogMethodInput[], method: { name: M } & MethodConfig, logger: LogConfig<M>) => LogMethodInput[])[];

/**
* A list of functions to handle input post processing
* @default []
* @example [(lines) => lines]
*/
postProcessors?: ((lines: string[], method: { name: M } & MethodConfig, logger: LogConfig<M>) => string[])[];
};

/**
Expand Down Expand Up @@ -145,7 +159,7 @@ export const pad = (
*/
export const createLogger = <A extends string>(
methods: MethodList<A> | MethodList<A>[],
config: Partial<LogConfig> = {},
config: Partial<LogConfig<A>> = {},
outputFunctions: GenericLogFunction | GenericLogFunction[] = console.log
) => {
const functions: GenericLogFunction[] = Array.isArray(outputFunctions)
Expand All @@ -158,7 +172,7 @@ export const createLogger = <A extends string>(
: methods;

// Fill default values incase not overridden by arg
const completeConfig: LogConfig = {
const completeConfig: Required<LogConfig<A>> = {
divider: ' ',
newLine: '├-',
newLineEnd: '└-',
Expand All @@ -167,6 +181,8 @@ export const createLogger = <A extends string>(
color: true,
exclude: [],
filter: undefined,
preProcessors: [],
postProcessors: [],
...config,
};

Expand Down Expand Up @@ -261,8 +277,14 @@ export const createLogger = <A extends string>(
)
return;

let inputs = s;

for(const processor of completeConfig.preProcessors) {
inputs = processor(inputs, { name: methodHandle as A, ...method }, completeConfig);
}

// Generate the value we should output
const value = s
const lines = inputs
.map((value) => {
if (typeof value !== 'string') {
value = inspect(
Expand Down Expand Up @@ -292,8 +314,15 @@ export const createLogger = <A extends string>(
? newLineEndPadding
: newLinePadding) + method.divider) +
value
)
.join('\n');
);

let parsedLines = lines;

for(const processor of completeConfig.postProcessors) {
parsedLines = processor(parsedLines, { name: methodHandle as A, ...method }, completeConfig);
}

const value = parsedLines.join('\n');

// Run each of the final functions
for (const a of functions) a(value);
Expand Down
2 changes: 1 addition & 1 deletion tests/logger.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import chalk from 'chalk';

import { createLogger, Logger, shimLog } from '../src';
import { createLogger, Logger } from '../src';

const logFunction = jest.fn();

Expand Down
51 changes: 51 additions & 0 deletions tests/postprocessors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import chalk from 'chalk';

import { createLogger, Logger } from '../src';

const logFunction = jest.fn();

describe('Post Process Logging', () => {
let logger: Logger<'ok'>;

beforeAll(() => {
logger = createLogger(
{
ok: {
label: chalk.greenBright`[OK]`,
newLine: '| ',
newLineEnd: '\\-',
},
},
{
padding: 'PREPEND',
color: false,
postProcessors: [
(lines, { name }) => {
let index = 0;

return lines.map(it => `[Called ${name} ${++index} times] ${it}`);
}
]
},
logFunction
);
});

afterEach(() => {
jest.clearAllMocks();
});

it('should log with pre-processor', () => {
logger.ok(
'This is the best logging library',
'It\'s not even a question',
'It even supports multi\nline logs'
);
expect(logFunction).toBeCalledWith(
`[Called ok 1 times] ${chalk.greenBright('[OK]')} This is the best logging library\n` +
'[Called ok 2 times] | It\'s not even a question\n' +
'[Called ok 3 times] | It even supports multi\n' +
'[Called ok 4 times] \\- line logs'
);
});
});
51 changes: 51 additions & 0 deletions tests/preprocessors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import chalk from 'chalk';

import { createLogger, Logger } from '../src';

const logFunction = jest.fn();

describe('Pre Process Logging', () => {
let logger: Logger<'ok'>;

beforeAll(() => {
logger = createLogger(
{
ok: {
label: chalk.greenBright`[OK]`,
newLine: '| ',
newLineEnd: '\\-',
},
},
{
padding: 'PREPEND',
color: false,
preProcessors: [
(inputs, { name }) => {
let index = 0;

return inputs.map(it => `[Called ${name} ${++index} times] ${it}`);
}
]
},
logFunction
);
});

afterEach(() => {
jest.clearAllMocks();
});

it('should log with pre-processor', () => {
logger.ok(
'This is the best logging library',
'It\'s not even a question',
'It even supports multi\nline logs'
);
expect(logFunction).toBeCalledWith(
`${chalk.greenBright('[OK]')} [Called ok 1 times] This is the best logging library\n` +
' | [Called ok 2 times] It\'s not even a question\n' +
' | [Called ok 3 times] It even supports multi\n' +
' \\- line logs'
);
});
});
4 changes: 2 additions & 2 deletions tests/randomlogconfig.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import chalk from 'chalk';

import { createLogger, Logger } from '../src';
import { createLogger, GenericLogFunction, Logger } from '../src';

const logFunction = jest.fn<void, [string]>();

Expand Down Expand Up @@ -38,7 +38,7 @@ describe('Random Config', () => {
},
],
{ padding: 'PREPEND', color: false },
logFunction
logFunction as GenericLogFunction
);
});

Expand Down

0 comments on commit fd9f1ef

Please sign in to comment.