]> git.r.bdr.sh - rbdr/cologne/blame_incremental - README.md
Set git depth to 0
[rbdr/cologne] / README.md
... / ...
CommitLineData
1# Cologne
2
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
5the fact.
6
7## Usage
8
9Install from npm
10
11```
12$ npm install --save cologne
13```
14
15Create an instance
16
17```javascript
18const { Cologne, Loggers, Formatters } = require('cologne');
19
20const co = new Cologne({
21 from: 'Special Worker Logger',
22 loggers: [
23 new Loggers.Console({
24 formatter: new Formatters.Token({
25 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
26 })
27 })
28 ]
29});
30```
31
32This example would create a cologne instance with a console logger that
33uses a Token formatter. (More on loggers and formatters below.);
34
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.
43* **log, info, notice, warn, error**: Generates a log object with the
44 appropriate severity level and sends it to all loggers.
45
46## Loggers
47
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
51to the browser console.
52
53`#log()` will receive any number of `Cologne Log Objects`. For a detailed
54reference of this format, see further below.
55
56Cologne includes two loggers out of the box:
57
58* `Loggers.Console` logs to the JS console
59* `Loggers.File` appends to a file
60
61### Loggers.Console
62
63This logger communicates with the Javascript console. It uses the log level
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
68to the `#format()` method: it should receive a cologne log object and respond
69with a string.
70
71```javascript
72new Loggers.Console({
73 formatter : new Formatters.Token({
74 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
75 })
76});
77```
78
79### Loggers.File
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
85It MUST include a `file` property on initialization, otherwise it will throw
86an exception.
87
88```javascript
89new Loggers.File({
90 file: '/var/log/server_log.log',
91 formatter : new Formatters.Token({
92 formatString: '[{{_ansi:_level}}{{_timestamp}}{{_ansi:reset}}]{{_from}}: {{message}}'
93 })
94});
95```
96
97### More Loggers?
98
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.
101
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
104to `#log()` is a valid logger:
105
106```javascript
107// A valid, very minimalistic logger
108const simpleLogger = {
109 log: function(...logs) {
110
111 for (const log of logs) {
112 this._doSomeMagic(logs);
113 }
114 },
115
116 _doSomeMagic: function(log) {
117
118 console.log(log + "... but magical!");
119 }
120};
121
122logger.addLogger(simpleLogger);
123```
124
125
126## Formatters
127
128Cologne doesn't need formatters to work, and in fact they're optional in
129the included loggers. But if you would like to make your logs prettier,
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
134it should return a string.
135
136We include some formatters so you can get running real quicklike:
137
138* `Formatters.Simple` a simple predefined formatter
139* `Formatters.Token` a formatter that lets you define format
140 strings that it will use to build your final log.
141
142### Formatters.Simple
143
144This is the lazy formatter, it just outputs the string in the following
145format:
146
147```
148'[{{_timestamp}}][{{_levelString}}]{{_from}}: {{message}}'
149```
150
151Where `_timestamp` is converted to ISO.
152
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
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.
161
162#### Usage
163
164```javascript
165new Formatters.Simple({
166 colorize: true
167});
168```
169
170### Example Output
171
172```
173co.log("hello world");
174// -> [2016-01-21T05:50:36.505Z][INFO] Server Logger: hello world
175```
176
177### Formatters.Token
178
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.
184
185#### Accepted Options
186
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
189 formatString. Defaults to `/{{(.*?)}}/g`
190* `isoDate` <Boolean> : Whether or not to convert `_timestamp` to ISO
191 date. Defaults to true. Otherwise it'll use the raw timestamp.
192
193#### Usage
194
195```javascript
196new Formatters.Token({
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:
231
232```javascript
233const sparkleFormatter = {
234 format: function(logObject) {
235
236 return `✨${logObject.message}✨`;
237 }
238}
239
240logger.addLogger(new Loggers.Console({
241 formatter: sparkleFormatter
242}));
243```
244
245## The Cologne Log Format
246
247The cologne log format is a JSON based log format, based on the cobalt
248log format, which is in turn based on Graylog's GELF. However, where GELF
249treats all internal fields without a prefix, and all user fields with a
250prefix, we do it backwards so it's easier to extend the object with
251metadata from existing objects.
252
253You could try to build it on your own, but you can use `#buildLog()`
254to build it without logging.
255
256### Fields
257
258* **\_timestamp** : A bigint timestamp in nanoseconds
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
261 version of cologne log format it's using. It's `2.0.0` right now.
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)
266
267### A word on Log Levels
268
269The log levels in cologne correspond to the syslog levels, and the
270levelStrings correspond to the priority keywords:
271
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