Commit 9baa0965
9baa0965e4bfMerged
Maxence Lecanu <[email protected]> · 4 years ago · 9 files · +1 added · ~8 modified
Description
feat: improve README
Details
- Commit
- 9baa0965e4bf
- Parent
- 2a887b162aa7
README.mdmodifiedView file
@@ -4,7 +4,7 @@
44
55
`hellog` is a general-purpose logging library.66
7-
It offers a `console.log`-like API and formatting, colored lines and timestamps (or not if desired), all that with 0 dependencies.7+
It offers a `console.log`-like API and formatting, **extensible type-safety** colored lines and timestamps (or not if desired), all that with 0 dependencies.88
99
## Install1010
@@ -20,20 +20,25 @@
2020
const logger = new Hellog();2121
2222
const obj = {23-
some: 'bar',2423
foo: {25-
nested: { bar: 'test', test: 'bar', hello: 2 },24+
foo: {25+
foo: {26+
foo: {27+
foo: 'bar',28+
},29+
},30+
},2631
},2732
};2833
2934
logger.log(obj);30-
logger.success(obj);35+
logger.success('Hello world !');3136
logger.debug(obj);3237
logger.error(new Error('test'));3338
logger.warn(new Error('test'));3439
```3540
36-
41+
3742
3843
## Transport and options3944
@@ -44,20 +49,12 @@
4449
```js4550
const { Hellog, transports } = require('hellog');4651
47-
const transport = new transports.Console({48-
showLevel: true,49-
timestamp: true,50-
});52+
const transport = new transports.Console();5153
5254
const logger = new Hellog({5355
transports: [transport],5456
});5557
```56-
57-
#### Options58-
59-
`timestamp` (`boolean`): _Whether or not to display the log time_60-
`showLevel` (`boolean`): _Whether or not to display the log level_6158
6259
### File6360
@@ -128,3 +125,177 @@
128125
2021-12-26 15:20:42 | [warning] | at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)129126
2021-12-26 15:20:42 | [warning] | at node:internal/main/run_main_module:17:47130127
```128+
129+
#### Options130+
131+
##### `outType: 'json' | 'string'`132+
133+
Defaults to `"json"`, the type of output of the file transport134+
135+
##### `filename: string`136+
137+
Defaults to `"output.log"`, the path to the file where logs are written. Can absolute or relative. However, we recommend using absolute paths.138+
139+
## Extensibilty140+
141+
The logging functionalities of `Hellog` are designed to be extensible. You can add personalized behaviour to the following elements of the logger:142+
143+
- Message context elaboration144+
- Message formatting on a per-transport basis145+
146+
Hellog is also designed to guarantee type-safety even with your custom implementations !147+
148+
### Life cycle149+
150+
To better understand where you can perform custom logic, let's quickly review the lifecycle of a message within the logger.151+
152+
_The logger is called_153+
154+
```js155+
new Hellog().log({ foo: bar }, 'Hello world');156+
```157+
158+
#### **Context elaboration**159+
160+
The very first thing done by `Hellog` is converting these inputs into a string.161+
162+
> We use `util.format` to do so, the same function used in the global `console`. That is the reason why `Hellog` can offer a console-like API.163+
164+
Once we have a string, a context object is created. At this point, the type of the context object is `PreparedMessage`.165+
166+
```ts167+
{168+
timestamp: Date,169+
message: string170+
level: LogLevel171+
}172+
```173+
174+
Then, for each transport, it's `log` method is called. This method is guaranteed to exist, because it is on the `BaseTransport` abstract class, extended by all transports classes.175+
176+
Here the default implementation of the `log` method on the `BaseTransport class`. Let's break this down.177+
178+
```ts179+
export abstract class BaseTransport {180+
//...181+
182+
log(log: T) {183+
const messages = this.prepareTransport(log);184+
const fMessages = messages.map((message) => this.format(message));185+
fMessages.forEach((fMessage) => this.transport(fMessage));186+
}187+
188+
//...189+
}190+
```191+
192+
#### **Transport preparation**193+
194+
In `Hellog`, messages are formatted and displayed on a _per-line_ basis. Meaning here that if your log spans on mutliple lines, it is breaked into a list of lines on the `"\n"` character.195+
196+
Each one of these lines will be formatted during the rest of the execution.197+
198+
> **This behaviour can be overriden when writing your own transport class.** For example, the `File` transport is implemented as follows:199+
200+
```ts201+
export class FileTransport {202+
//...203+
204+
prepareTransport(log: T): T[] {205+
if (this.outType === 'json') {206+
return [log];207+
} else {208+
return log.message.split('\n').map((message) => ({ ...log, message }));209+
}210+
}211+
212+
//...213+
}214+
```215+
216+
Here, we don't want to break line when outputting JSON message, this is left to any system that will monitor this and read the log file.217+
218+
**Each input in the resulting list is passed to the `format` method.**219+
220+
#### **Formatting**221+
222+
Formatting is performed on a **per-line** basis. Each transport is instanciated with a list of formatters, that extends the Formatter type.223+
224+
```ts225+
export type Formatter<T extends PreparedMessage = PreparedMessage> = (226+
current: string,227+
context: T228+
) => string;229+
```230+
231+
For each line, every formatters are called in the order defined by the list provided during class instanciation. By default the base transport uses three standard formats (provided by the library itself).232+
233+
Here is the default implementation of the `format` step:234+
235+
```ts236+
export abstract class BaseTransport {237+
formatters: Formatter[] = [addLevel(), addTimestamp(), colorize()];238+
239+
//...240+
241+
format(preparedLine: T): string {242+
let formattedMessage = preparedLine.message;243+
for (const formatter of this.formatters) {244+
formattedMessage = formatter(formattedMessage, preparedLine);245+
}246+
return formattedMessage;247+
}248+
249+
//...250+
}251+
```252+
253+
> You can override this behaviour when doing your own transport class.254+
255+
#### Message transportation256+
257+
Once the log is nothing more than a list of string, the `transport` method of the transport is called for each resulting string.258+
259+
Very various thing happen at this point. by default, a simple `console.log` is performed here. The `FileTransport` writes into a `fs.WriteStream`. You can implement a transport where the lines are sent over HTTP. [Here are some examples](https://www.youtube.com/watch?v=1MkzF9cFs2I).260+
261+
### Improve formatting262+
263+
### Improve context elaboration264+
265+
If you need to add additional data into the `PreparedMessage` object being passed along this cycle, you can using the `additionalContext` when instanciating the `Hellog` object.266+
267+
You can even do it with type safety and completion !268+
269+
```ts270+
import { Hellog } from './logger';271+
272+
interface ExtendedContext extends PreparedMessage {273+
id: number;274+
}275+
276+
const displayId: Formatter<ExtendedContext> = (277+
current: string,278+
context: ExtendedContext279+
) => {280+
return `${context.id} | ${current}`;281+
};282+
283+
const csle = new transports.Console<ExtendedContext>({284+
formatters: [285+
formatters.addLevel(true),286+
displayId,287+
formatters.addTimestamp(),288+
formatters.colorize(),289+
],290+
});291+
292+
const logger = new Hellog<ExtendedContext>({293+
transports: [csle],294+
additionalContext: (message) => ({295+
...message,296+
id: Math.floor(Math.random() * 1000),297+
}),298+
});299+
300+
logger.success(new Error('test'));301+
```assets/get-started.pngaddedView file
Loading diff…
lib/entities/formatters.tsmodifiedView file
Loading diff…
lib/formats/colorize.tsmodifiedView file
Loading diff…
lib/formats/timestamp.tsmodifiedView file
Loading diff…
lib/index.tsmodifiedView file
Loading diff…
lib/logger.tsmodifiedView file
Loading diff…
lib/transports/base.tsmodifiedView file
Loading diff…
lib/transports/console.tsmodifiedView file
Loading diff…