]> git.r.bdr.sh - rbdr/cologne/blame - README.md
Move ansi codes to an object
[rbdr/cologne] / README.md
CommitLineData
bfd26c00 1# Cologne
08ce17a6 2
8d2dfbab
RBR
3Cologne is a logger multiplexer that uses a JSON log format inspired in gelf.
4It can be instantiated with several loggers, or they can be changed after
bfd26c00
RBR
5the fact.
6
7## Usage
8
8d2dfbab 9Install from npm
87881a5c 10
2aa083b6 11```
8d2dfbab 12$ npm install --save cologne
2aa083b6
BB
13```
14
8d2dfbab 15Create an instance
2aa083b6 16
bfd26c00 17```javascript
8d2dfbab 18const { Cologne, Loggers, Formatters } = require('cologne');
bfd26c00 19
8d2dfbab
RBR
20const co = new Cologne({
21 from: 'Special Worker Logger',
bfd26c00 22 loggers: [
8d2dfbab
RBR
23 new Loggers.Console({
24 formatter: new Formatters.Token({
bfd26c00
RBR
25 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
26 })
27 })
28 ]
87881a5c
BB
29});
30```
31
bfd26c00
RBR
32This example would create a cologne instance with a console logger that
33uses a Token formatter. (More on loggers and formatters below.);
87881a5c 34
bfd26c00
RBR
35## Quick API Reference
36
37* **addLogger(logger)**: Adds a logger to the cologne instance.
38* **removeLogger(logger)**: Removes a logger from the cologne instance.
39* **buildLog(item, level, [meta])**: Generates a cologne log object as if you had
40 logged an item (it will do this automatically when you log anything.)
41 level defaults to 6. You can optionally send it an object to extend
42 the object with.
941d0901
BB
43* **log, info, notice, warn, error**: Generates a log object with the
44 appropriate severity level and sends it to all loggers.
87881a5c 45
bfd26c00 46## Loggers
87881a5c 47
bfd26c00
RBR
48Cologne loggers are any object that responds to the `#log()` method.
49This methoud should be able to receive any number of arguments and
50log them independently. Similar to how you can send multiple arguments
8d2dfbab 51to the browser console.
87881a5c 52
8d2dfbab
RBR
53`#log()` will receive any number of `Cologne Log Objects`. For a detailed
54reference of this format, see further below.
2e7f5498 55
8d2dfbab 56Cologne includes two loggers out of the box:
2e7f5498 57
8d2dfbab
RBR
58* `Loggers.Console` logs to the JS console
59* `Loggers.File` appends to a file
bfd26c00 60
8d2dfbab 61### Loggers.Console
bfd26c00 62
8d2dfbab 63This logger communicates with the Javascript console. It uses the log level
bfd26c00
RBR
64to trigger the appropriate method, so `error` logs would go to stderr
65as expected when calling `console.error`.
66
67This logger can be sent a `formatter`, which is an object that responds
8d2dfbab 68to the `#format()` method: it should receive a cologne log object and respond
bfd26c00
RBR
69with a string.
70
71```javascript
8d2dfbab
RBR
72new Loggers.Console({
73 formatter : new Formatters.Token({
bfd26c00
RBR
74 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
75 })
76});
2e7f5498 77```
2e7f5498 78
8d2dfbab 79### Loggers.File
bfd26c00
RBR
80
81This logger opens a writable stream to a file, to which it will append
82everything. Like the Console logger it supports a `formatter` property
83that will respond to the `#format()` method.
84
8d2dfbab
RBR
85It MUST include a `file` property on initialization, otherwise it will throw
86an exception.
bfd26c00
RBR
87
88```javascript
8d2dfbab 89new Loggers.File({
bfd26c00 90 file: '/var/log/server_log.log',
8d2dfbab
RBR
91 formatter : new Formatters.Token({
92 formatString: '[{{_ansi:_level}}{{_timestamp}}{{_ansi:reset}}]{{_from}}: {{message}}'
bfd26c00
RBR
93 })
94});
95```
2e7f5498 96
bfd26c00 97### More Loggers?
87881a5c 98
bfd26c00
RBR
99We're working on a socket logger. It's separate so you don't have to
100install the socket dependencies if you don't want to.
87881a5c 101
941d0901
BB
102You can build your own logger easily for any method of transport you find
103necessary (e.g. mail, database, twitter, etc). Any object that responds
bfd26c00 104to `#log()` is a valid logger:
87881a5c
BB
105
106```javascript
107// A valid, very minimalistic logger
8d2dfbab
RBR
108const simpleLogger = {
109 log: function(...logs) {
110
111 for (const log of logs) {
112 this._doSomeMagic(logs);
bfd26c00
RBR
113 }
114 },
115
8d2dfbab
RBR
116 _doSomeMagic: function(log) {
117
118 console.log(log + "... but magical!");
87881a5c 119 }
bfd26c00 120};
87881a5c
BB
121
122logger.addLogger(simpleLogger);
123```
124
87881a5c 125
bfd26c00
RBR
126## Formatters
127
128Cologne doesn't need formatters to work, and in fact they're optional in
8d2dfbab 129the included loggers. But if you would like to make your logs prettier,
bfd26c00
RBR
130then you can use one of the included formatters or roll your own.
131
132Formatters are objects that respond to the `#format()` method. It will
133receive a single cologne log object (see fields it includes below), and
8d2dfbab 134it should return a string.
2e7f5498 135
bfd26c00
RBR
136We include some formatters so you can get running real quicklike:
137
8d2dfbab
RBR
138* `Formatters.Simple` a simple predefined formatter
139* `Formatters.Token` a formatter that lets you define format
bfd26c00
RBR
140 strings that it will use to build your final log.
141
8d2dfbab 142### Formatters.Simple
2e7f5498
BB
143
144This is the lazy formatter, it just outputs the string in the following
145format:
146
147```
bfd26c00 148'[{{_timestamp}}][{{_levelString}}]{{_from}}: {{message}}'
2e7f5498
BB
149```
150
151Where `_timestamp` is converted to ISO.
152
bfd26c00
RBR
153#### Accepted Options
154
155* `colorize` <Boolean>: whether or not to add color. False by default.
156
157By default we don't colorize the output, but if you enable the flag this
8d2dfbab
RBR
158formatter will add a bit of color in the level string. Red for error, crit,
159alert, and emerg; yellow for warn; blue for info; green for debug; and white
160for everything else.
2e7f5498 161
bfd26c00
RBR
162#### Usage
163
164```javascript
8d2dfbab 165new Formatters.Simple({
bfd26c00
RBR
166 colorize: true
167});
2e7f5498 168```
bfd26c00
RBR
169
170### Example Output
171
172```
173co.log("hello world");
174// -> [2016-01-21T05:50:36.505Z][INFO] Server Logger: hello world
2e7f5498 175```
87881a5c 176
8d2dfbab 177### Formatters.Token
87881a5c 178
bfd26c00
RBR
179The token formatter lets you build strings with simple tokens. When
180instantiating, you can specify a `formatString` to interpolate
181properties from the logObject. The default version looks for tokens
182inside double curly braces like `{{message}}` or `{{_level}}`. If
183you don't like it, you can specify your own.
2e7f5498 184
bfd26c00 185#### Accepted Options
2e7f5498 186
bfd26c00
RBR
187* `formatString` <String>: The string used to replace. Defaults to `"{{message}}"`
188* `replaceRule` <String>: The regex rule to use for replacement of tokens in the
2e7f5498 189 formatString. Defaults to `/{{(.*?)}}/g`
2e7f5498 190* `isoDate` <Boolean> : Whether or not to convert `_timestamp` to ISO
bfd26c00
RBR
191 date. Defaults to true. Otherwise it'll use the raw timestamp.
192
193#### Usage
194
195```javascript
8d2dfbab 196new Formatters.Token({
bfd26c00
RBR
197 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
198});
199```
200
201#### ANSI tokens
202
203If you want to add color to your logs, you can use the special \_ansi
204token. It has several options which you can call like `{{_ansi:red}}`
205and `{{_ansi:reset}}`. Here's a list of all the ansi stuff you can use:
206
207* `bold`: makes text bold
208* `italics`: makes text italics
209* `underline`: makes text underlined
210* `inverse`: inverts foreground and background
211* `strikethrough`: strikethrough text
212* `bold_off`, `italics_off`, `underline_off`, `inverse_off`, and
213 `strikethrough_off`: turn off the specified effect.
214* `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`,
215 and `default`: change the foreground color of your text.
216* `black_bg`, `red_bg`, `green_bg`, `yellow_bg`, `blue_bg`, `magenta_bg`,
217 `cyan_bg`, `white_bg`, and `default_bg`: change the background color of your
218 text.
219* `reset`: makes everything normal again.
220* `_level`: this is a special code that will set a color depending on
221 the level of the log: debug gets green, info and notice blue, warn is
222 yellow, and anything worse is red.
223
224### More Formatters?
225
226You can create your own formatters by creating an object that responds
227to the `#format()` method, knows how to handle cologne log objects and
228returns a string.
229
230Here's an example of a logger that surrounds a log with sparkles:
87881a5c
BB
231
232```javascript
8d2dfbab
RBR
233const sparkleFormatter = {
234 format: function(logObject) {
235
236 return `✨${logObject.message}✨`;
87881a5c
BB
237 }
238}
239
8d2dfbab
RBR
240logger.addLogger(new Loggers.Console({
241 formatter: sparkleFormatter
87881a5c
BB
242}));
243```
244
bfd26c00
RBR
245## The Cologne Log Format
246
247The cologne log format is a JSON based log format, based on the cobalt
8d2dfbab 248log format, which is in turn based on Graylog's GELF. However, where GELF
bfd26c00 249treats all internal fields without a prefix, and all user fields with a
8d2dfbab
RBR
250prefix, we do it backwards so it's easier to extend the object with
251metadata from existing objects.
87881a5c 252
bfd26c00
RBR
253You could try to build it on your own, but you can use `#buildLog()`
254to build it without logging.
941d0901 255
bfd26c00 256### Fields
87881a5c 257
8d2dfbab 258* **\_timestamp** : A bigint timestamp in nanoseconds
bfd26c00
RBR
259* **\_cologneLog** <String> : This is how we know if the log is already
260 formatted and ready to go. This field is a string containing the
8d2dfbab 261 version of cologne log format it's using. It's `2.0.0` right now.
bfd26c00
RBR
262* **\_from**: The sender of the log (Defaults to Generic Cologne Logger)
263* **\_level**: The level of the log (Defaults to 6)
264* **\_levelString**: The string corresponding to the log level (e.g. 7 ->
265 debug, 3 -> error, 0 -> emerg)
87881a5c 266
bfd26c00 267### A word on Log Levels
87881a5c 268
bfd26c00
RBR
269The log levels in cologne correspond to the syslog levels, and the
270levelStrings correspond to the priority keywords:
87881a5c 271
bfd26c00
RBR
272* `0 -> emerg`
273* `1 -> alert`
274* `2 -> crit`
275* `3 -> error`
276* `4 -> warning`
277* `5 -> notice`
278* `6 -> info`
279* `7 -> debug`
280
281This is useful when deciding how to log. You could even have a logger
282filter out unnecessary levels (eg. If you have a reporting logger that
283only reports error or worse.)
284
285## Further Improvements
286
287* Improve the API for buildLog
288* More loggers & formatters (will not be distributed in core cologne)
289* Improve tests