]> git.r.bdr.sh - rbdr/cologne/blob - README.md
Run lint and test on merge requests
[rbdr/cologne] / README.md
1 # Cologne
2
3 Cologne is a logger multiplexer that uses a JSON log format inspired in gelf.
4 It can be instantiated with several loggers, or they can be changed after
5 the fact.
6
7 ## Usage
8
9 Install from npm
10
11 ```
12 $ npm install --save cologne
13 ```
14
15 Create an instance
16
17 ```javascript
18 const { Cologne, Loggers, Formatters } = require('cologne');
19
20 const 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
32 This example would create a cologne instance with a console logger that
33 uses 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
48 Cologne loggers are any object that responds to the `#log()` method.
49 This methoud should be able to receive any number of arguments and
50 log them independently. Similar to how you can send multiple arguments
51 to the browser console.
52
53 `#log()` will receive any number of `Cologne Log Objects`. For a detailed
54 reference of this format, see further below.
55
56 Cologne 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
63 This logger communicates with the Javascript console. It uses the log level
64 to trigger the appropriate method, so `error` logs would go to stderr
65 as expected when calling `console.error`.
66
67 This logger can be sent a `formatter`, which is an object that responds
68 to the `#format()` method: it should receive a cologne log object and respond
69 with a string.
70
71 ```javascript
72 new Loggers.Console({
73 formatter : new Formatters.Token({
74 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
75 })
76 });
77 ```
78
79 ### Loggers.File
80
81 This logger opens a writable stream to a file, to which it will append
82 everything. Like the Console logger it supports a `formatter` property
83 that will respond to the `#format()` method.
84
85 It MUST include a `file` property on initialization, otherwise it will throw
86 an exception.
87
88 ```javascript
89 new 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
99 We're working on a socket logger. It's separate so you don't have to
100 install the socket dependencies if you don't want to.
101
102 You can build your own logger easily for any method of transport you find
103 necessary (e.g. mail, database, twitter, etc). Any object that responds
104 to `#log()` is a valid logger:
105
106 ```javascript
107 // A valid, very minimalistic logger
108 const 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
122 logger.addLogger(simpleLogger);
123 ```
124
125
126 ## Formatters
127
128 Cologne doesn't need formatters to work, and in fact they're optional in
129 the included loggers. But if you would like to make your logs prettier,
130 then you can use one of the included formatters or roll your own.
131
132 Formatters are objects that respond to the `#format()` method. It will
133 receive a single cologne log object (see fields it includes below), and
134 it should return a string.
135
136 We 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
144 This is the lazy formatter, it just outputs the string in the following
145 format:
146
147 ```
148 '[{{_timestamp}}][{{_levelString}}]{{_from}}: {{message}}'
149 ```
150
151 Where `_timestamp` is converted to ISO.
152
153 #### Accepted Options
154
155 * `colorize` <Boolean>: whether or not to add color. False by default.
156
157 By default we don't colorize the output, but if you enable the flag this
158 formatter will add a bit of color in the level string. Red for error, crit,
159 alert, and emerg; yellow for warn; blue for info; green for debug; and white
160 for everything else.
161
162 #### Usage
163
164 ```javascript
165 new Formatters.Simple({
166 colorize: true
167 });
168 ```
169
170 ### Example Output
171
172 ```
173 co.log("hello world");
174 // -> [2016-01-21T05:50:36.505Z][INFO] Server Logger: hello world
175 ```
176
177 ### Formatters.Token
178
179 The token formatter lets you build strings with simple tokens. When
180 instantiating, you can specify a `formatString` to interpolate
181 properties from the logObject. The default version looks for tokens
182 inside double curly braces like `{{message}}` or `{{_level}}`. If
183 you 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
196 new Formatters.Token({
197 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
198 });
199 ```
200
201 #### ANSI tokens
202
203 If you want to add color to your logs, you can use the special \_ansi
204 token. It has several options which you can call like `{{_ansi:red}}`
205 and `{{_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
226 You can create your own formatters by creating an object that responds
227 to the `#format()` method, knows how to handle cologne log objects and
228 returns a string.
229
230 Here's an example of a logger that surrounds a log with sparkles:
231
232 ```javascript
233 const sparkleFormatter = {
234 format: function(logObject) {
235
236 return `✨${logObject.message}✨`;
237 }
238 }
239
240 logger.addLogger(new Loggers.Console({
241 formatter: sparkleFormatter
242 }));
243 ```
244
245 ## The Cologne Log Format
246
247 The cologne log format is a JSON based log format, based on the cobalt
248 log format, which is in turn based on Graylog's GELF. However, where GELF
249 treats all internal fields without a prefix, and all user fields with a
250 prefix, we do it backwards so it's easier to extend the object with
251 metadata from existing objects.
252
253 You could try to build it on your own, but you can use `#buildLog()`
254 to 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
269 The log levels in cologne correspond to the syslog levels, and the
270 levelStrings 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
281 This is useful when deciding how to log. You could even have a logger
282 filter out unnecessary levels (eg. If you have a reporting logger that
283 only 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