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