Skip to content

Commit

Permalink
feat: better filters / appenders API (#4)
Browse files Browse the repository at this point in the history
* feat: add default message filter for draftlog appender

* feat: another API for appenders / filters

* feat: display logger tag for verbose messages

* docs: updated documentation for logger

* config: added readme field
  • Loading branch information
kshutkin authored Dec 29, 2021
1 parent e0ea29c commit 9f0ab27
Show file tree
Hide file tree
Showing 24 changed files with 2,081 additions and 913 deletions.
10 changes: 6 additions & 4 deletions draftlog-appender/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"url": "https://github.com/kshutkin/niceties/issues"
},
"homepage": "https://github.com/kshutkin/niceties/blob/main/draftlog-appender/README.md",
"readme": "README.md",
"scripts": {
"build": "rimraf ./dist && rollup -c",
"dev": "rimraf ./dist && rollup -c -w",
Expand Down Expand Up @@ -71,11 +72,12 @@
"semantic-release-monorepo": "7.0.5",
"ts-jest": "27.0.7",
"typescript": "4.4.x",
"update-monorepo-package-json": "0.1.6"
"update-monorepo-package-json": "0.2.0"
},
"peerDependencies": {
"@niceties/logger": "^1.0.4"
},
"dependencies": {
"@niceties/logger": "^1.0.4",
"draftlog": "^1.0.13"
},
"readme": "ERROR: No README data found!"
}
}
10 changes: 9 additions & 1 deletion draftlog-appender/src/details/canvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Formatter } from '@niceties/logger/types';

import { ItemStatus, Model, ModelItem } from './model';
import { Spinner } from '../spinners';
import { Action } from '@niceties/logger';

interface DraftlogConfig {
defaults: {
Expand Down Expand Up @@ -38,7 +39,14 @@ export function createCanvas(spinner: Spinner, formatter: Formatter, ident: numb
}
if (dirty || item.dirty_ || item.status_) {
const prefix = getPrefix(item.status_ as ItemStatus, model.tick_);
updater(formatter(item.text_, item.loglevel_, prefix, ident * (stack.length - 1)));
updater(formatter({
loglevel: item.loglevel_,
message: item.text_,
context: item.context_,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
action: (item.status_ === undefined ? Action.log : undefined) as unknown as any,
tag: item.tag_
}, prefix, ident * (stack.length - 1)));
if (item.dirty_) {
item.dirty_ = false;
dirty = true;
Expand Down
7 changes: 5 additions & 2 deletions draftlog-appender/src/details/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ export interface ModelItem {
loglevel_: LogLevel;
ref_?: WeakRef<never>;
parentId_?: number;
tag_?: string;
next_?: ModelItem;
children_: ModelItem[];
dirty_?: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
context_?: any;
}

export type Model = {
Expand All @@ -31,9 +34,9 @@ export function createModel(logAboveSpinners: boolean): [(logMessage: LogMessage
items_: []
};
const itemById: {[key: number]: ModelItem} = Object.create(null);
return [({ message: text, inputId, action, loglevel, ref, parentId }: LogMessage): Model => {
return [({ message: text, inputId, action, loglevel, ref, parentId, context, tag }: LogMessage): Model => {
// item has status undefined, so it is static by default
const item: ModelItem = { text_: text, loglevel_: loglevel, ref_: ref, parentId_: parentId, children_: [], dirty_: true };
const item: ModelItem = { text_: text, loglevel_: loglevel, ref_: ref, parentId_: parentId, children_: [], dirty_: true, context_: context, tag_: tag };
if (action === Action.start) {
item.status_ = ItemStatus.inprogress;
}
Expand Down
16 changes: 11 additions & 5 deletions draftlog-appender/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { appender } from '@niceties/logger/core';
import { filterMessages } from '@niceties/logger/appender-utils';
import { appender } from '@niceties/logger/global-appender';
import { terminalSupportsUnicode, createFormatter } from '@niceties/logger/format-utils';
import { colors, unicodePrefixes, asciiPrefixes } from '@niceties/logger/default-formatting';
import { colors, unicodePrefixes, asciiPrefixes, tagFactory } from '@niceties/logger/default-formatting';
import { createDraftlogAppender } from './core';
import { dots, line } from './spinners';
import { Action, LogLevel, LogMessage } from '@niceties/logger';

const supportsUnicode = terminalSupportsUnicode();
const spinner = supportsUnicode ? dots : line;
const formatter = createFormatter(colors, supportsUnicode ? unicodePrefixes : asciiPrefixes);

appender(createDraftlogAppender(spinner, formatter, false, 2));
const formatter = createFormatter(colors, supportsUnicode ? unicodePrefixes : asciiPrefixes, tagFactory);

let minLogLevel = LogLevel.info;
appender(filterMessages<Error, { setMinLevel(logLevel: LogLevel): void; }>(
(message: LogMessage) => message.loglevel >= minLogLevel || message.action !== Action.log,
createDraftlogAppender(spinner, formatter, false, 2), // eslint-disable-line indent
{ setMinLevel(logLevel: LogLevel) { minLogLevel = logLevel; } } // eslint-disable-line indent
));
7 changes: 4 additions & 3 deletions draftlog-appender/tests/appender.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const testSpinner = {

const finishedPrefixes: Prefixes = ['', 'ok', 'warn', 'error'];
const colors: ColorFormatters = [,,,,];
const tagFactory = (tag: string) => tag;

const waitFor = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));

Expand All @@ -35,7 +36,7 @@ describe('draftlog appender', () => {
const ref = new WeakRef(testSpinner) as WeakRef<never>;

beforeEach(() => {
const formatter = createFormatter(colors, finishedPrefixes);
const formatter = createFormatter(colors, finishedPrefixes, tagFactory);
appender = createDraftlogAppender(testSpinner, formatter, false, 2);
draftLogDefaults = (draftlog as never as DraftlogConfig).defaults;
consoleUpdateMock = jest.fn<void, any[]>();
Expand Down Expand Up @@ -259,7 +260,7 @@ describe('draftlog appender animation', () => {
const ref = new WeakRef(testSpinner) as WeakRef<never>;

beforeEach(() => {
const formatter = createFormatter(colors, finishedPrefixes);
const formatter = createFormatter(colors, finishedPrefixes, tagFactory);
appender = createDraftlogAppender(testSpinner2, formatter, false, 2);
consoleUpdateMock = jest.fn<void, any[]>();
consoleDraftMock = jest.spyOn(global.console, 'draft').mockImplementation(() => (...args: any[]) => consoleUpdateMock(...args));
Expand Down Expand Up @@ -287,7 +288,7 @@ describe('prepend config', () => {
const ref = new WeakRef(testSpinner) as WeakRef<never>;

beforeEach(() => {
const formatter = createFormatter(colors, finishedPrefixes);
const formatter = createFormatter(colors, finishedPrefixes, tagFactory);
appender = createDraftlogAppender(testSpinner, formatter, true, 2);
consoleUpdateMock = jest.fn<void, any[]>();
consoleDraftMock = jest.spyOn(global.console, 'draft').mockImplementation(() => (...args: any[]) => consoleUpdateMock(...args));
Expand Down
8 changes: 6 additions & 2 deletions examples/index.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import "@niceties/draftlog-appender";
import { createLogger } from "@niceties/logger";
import { createLogger, appender } from "@niceties/logger";
import kleur from "kleur";

appender().setMinLevel(0);

const waitFor = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

setTimeout(() => {
const logger = createLogger();
const logger = createLogger('test tag');

logger('test', 0);

logger.start('I am going to be freed soon');

Expand Down
42 changes: 20 additions & 22 deletions logger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@ Experimental logger/reporter for async tasks.

# Installation

```
yarn add @niceties/logger
```

or

```
npm install --save @niceties/logger
```
Expand Down Expand Up @@ -47,11 +41,11 @@ try {
Logger factory:

```typescript
function createLogger<ErrorContext = Error>(...args: [] | [string | Identity] | [string, Identity]): ((message: string, loglevel?: LogLevel, context?: ErrorContext | undefined) => void) & {
start(message: string, loglevel?: LogLevel | undefined): void;
update(message: string, loglevel?: LogLevel | undefined): void;
finish(message: string, loglevel?: LogLevel | undefined): void;
withAppender(appender: Appender<ErrorContext>): ((message: string, loglevel?: LogLevel, context?: ErrorContext | undefined) => void) & any;
function createLogger<ErrorContext = Error>(...args: [] | [string | Identity | undefined] | [string, Identity]): ((message: string, loglevel?: LogLevel, context?: ErrorContext | undefined) => void) & {
start(message: string, loglevel?: LogLevel | undefined, context?: ErrorContext | undefined): void;
update(message: string, loglevel?: LogLevel | undefined, context?: ErrorContext | undefined): void;
finish(message: string, loglevel?: LogLevel | undefined, context?: ErrorContext | undefined): void;
appender(appender?: Appender<ErrorContext> | undefined): (message: LogMessage<ErrorContext>) => void;
};
```

Expand Down Expand Up @@ -91,36 +85,36 @@ try {
```

```typescript
start(message: string, loglevel?: LogLevel | undefined): void;
start(message: string, loglevel?: LogLevel | undefined, context?: ErrorContext | undefined): void;
```

Emits start event inside a logger. If loglevel provided it will be remembered and used as default loglevel in subsequent events in the same logger instance. Default loglevel (if argument is not provided) is `info`.

```typescript
update(message: string, loglevel?: LogLevel | undefined): void;
update(message: string, loglevel?: LogLevel | undefined, context?: ErrorContext | undefined): void;
```

Emits update event. Can be used to inform user that we are doing something else in the same async task. loglevel used to redefine default loglevel.

```typescript
finish(message: string, loglevel?: LogLevel | undefined): void;
finish(message: string, loglevel?: LogLevel | undefined, context?: ErrorContext | undefined): void;
```

Emits finish event. Can be used to inform user that task finished. loglevel is optional and equals initial loglevel if omitted.

```typescript
const log = createLogger()
.withAppender(someFancyAppender);
const logger = createLogger();
logger.appender(someFancyAppender);
```

Adds new appender for the specific inctance of logger. It is not mandatory to use the return value because no new instance of logger created and appender added to the existing instance.
Sets different appender for the specific instance of the logger.

```typescript
const log = createLogger()
.withFilter(predicate);
const logger = createLogger();
const appender = logger.appender();
```

Install filter on previosly installed appenders. It is not mandatory to use the return value because no new instance of logger created and filter added to the existing instance.
Returns current appender for the specific instance of the logger.

## Log levels

Expand Down Expand Up @@ -226,14 +220,18 @@ Default subpackage `'@niceties/logger'` exports types, `createLogger()` factory

Subpackage `'@niceties/logger/default-formatting'` exports formatting constants that is part of default configuration of the console appender.

Subpackage `'@niceties/logger/core'` exports `createLogger()` factory and `appender()`, `combineAppenders()`, `filterMessages()` functions.
Subpackage `'@niceties/logger/core'` exports `createLogger()` factory.

Subpackage `'@niceties/logger/simple'` exports `createLogger()` factory and `appender()`, `combineAppenders()`, `filterMessages()` function.
Subpackage `'@niceties/logger/simple'` exports `createLogger()` factory.

Subpackage `'@niceties/logger/console-appender'` exports `createConsoleAppender()` factory.

Subpackage `'@niceties/logger/format-utils'` exports `createFormatter()` and `terminalSupportsUnicode()` functions.

Subpackage `'@niceties/logger/global-appender'` exports `appender()` and `globalAppender`.

Subpackage `'@niceties/logger/appender-utils'` exports `combineAppenders()` and `filterMessages()`.

`simple` (default), `core` and `console-appender` exists as umd packages as well but probably require some effort to consume them.

# Prior art
Expand Down
3 changes: 3 additions & 0 deletions logger/appender-utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"types": "../dist/appender-utils.d.ts"
}
3 changes: 3 additions & 0 deletions logger/global-appender/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"types": "../dist/global-appender.d.ts"
}
29 changes: 21 additions & 8 deletions logger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@
"./format-utils": {
"require": "./dist/format-utils.cjs",
"default": "./dist/format-utils.mjs"
},
"./global-appender": {
"require": "./dist/global-appender.cjs",
"default": "./dist/global-appender.mjs"
},
"./appender-utils": {
"require": "./dist/appender-utils.cjs",
"default": "./dist/appender-utils.mjs"
}
},
"main": "./dist/index.cjs",
Expand All @@ -40,6 +48,8 @@
"default-formatting",
"core",
"console-appender",
"global-appender",
"appender-utils",
"format-utils",
"types",
"simple"
Expand All @@ -55,6 +65,7 @@
"url": "https://github.com/kshutkin/niceties/issues"
},
"homepage": "https://github.com/kshutkin/niceties/blob/main/logger/README.md",
"readme": "REAMDE.md",
"scripts": {
"build": "rimraf ./dist && rollup -c",
"dev": "rimraf ./dist && rollup -c -w",
Expand All @@ -70,23 +81,25 @@
"@semantic-release/git": "10.0.1",
"@semantic-release/npm": "8.0.2",
"@semantic-release/release-notes-generator": "10.0.2",
"@types/jest": "27.0.2",
"@typescript-eslint/eslint-plugin": "5.3.0",
"@typescript-eslint/parser": "5.3.0",
"@types/jest": "27.0.3",
"@types/node": "17.0.5",
"@typescript-eslint/eslint-plugin": "5.8.1",
"@typescript-eslint/parser": "5.8.1",
"conventional-changelog-angular": "5.0.13",
"eslint": "8.1.0",
"jest": "27.3.1",
"eslint": "8.5.0",
"jest": "27.4.5",
"lodash": "4.17.21",
"rimraf": "3.0.2",
"rollup": "2.60.1",
"rollup": "2.62.0",
"rollup-plugin-preprocess": "0.0.4",
"rollup-plugin-terser": "7.0.2",
"rollup-plugin-typescript2": "0.31.1",
"semantic-release": "18.0.0",
"semantic-release-monorepo": "7.0.5",
"ts-jest": "27.0.7",
"ts-jest": "27.1.2",
"tslib": "2.3.1",
"typescript": "4.4.x"
"typescript": "4.5.x",
"pkgbld": "1.1.1"
},
"dependencies": {
"kleur": "^4.1.4"
Expand Down
Loading

0 comments on commit 9f0ab27

Please sign in to comment.