Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce basic pre/post processor logic #96

Merged
merged 7 commits into from
Feb 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSDocs?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sowwy

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

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSDocs?

/**
* 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