]> git.r.bdr.sh - rbdr/cologne/blame_incremental - README.md
Recover from npm package
[rbdr/cologne] / README.md
... / ...
CommitLineData
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
6Cologne is a logger multiplexer that works mainly with a JSON format. It
7can be instantiated with several loggers, or they can be changed after
8the fact.
9
10## Usage
11
12Install from npm or add to your package.json:
13
14```
15$ npm install cologne
16```
17
18Create an instance:
19
20```javascript
21require('cologne');
22
23let 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
35This example would create a cologne instance with a console logger that
36uses a Token formatter. (More on loggers and formatters below.);
37
38## Do I need anything special?
39
40Node 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
55Cologne loggers are any object that responds to the `#log()` method.
56This methoud should be able to receive any number of arguments and
57log them independently. Similar to how you can send multiple arguments
58to the JS console.
59
60`#log()` will receive any number of `Cologne Log Objects`. To see what
61this format includes, check further below.
62
63We 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
70This logger communicates the Javascript console. It uses the log level
71to trigger the appropriate method, so `error` logs would go to stderr
72as expected when calling `console.error`.
73
74This logger can be sent a `formatter`, which is an object that responds
75to the `#format()` method: it should get a cologne log object and respond
76with a string.
77
78```javascript
79new Cologne.Logger.Console({
80 formatter : new Cologne.Formatter.Token({
81 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
82 })
83});
84```
85
86### Cologne.Logger.File
87
88This logger opens a writable stream to a file, to which it will append
89everything. Like the Console logger it supports a `formatter` property
90that will respond to the `#format()` method.
91
92It MUST include a `file` property on initialization, otherwise it won't
93know where to write and you'll get an exception and be sad.
94
95```javascript
96new 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
106We're working on a socket logger. It's separate so you don't have to
107install the socket dependencies if you don't want to.
108
109If you need to, you can roll your own. Check info on the interfaces
110below.
111
112You can build your own logger easily for any method of transport you find
113necessary (e.g. mail, database, twitter, etc). Any object that responds
114to `#log()` is a valid logger:
115
116```javascript
117// A valid, very minimalistic logger
118let 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
130logger.addLogger(simpleLogger);
131```
132
133
134## Formatters
135
136Cologne doesn't need formatters to work, and in fact they're optional in
137the included workers. But if you would like to make your logs prettier,
138then you can use one of the included formatters or roll your own.
139
140Formatters are objects that respond to the `#format()` method. It will
141receive a single cologne log object (see fields it includes below), and
142it should return a string. That's all there is to it.
143
144We 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
152This is the lazy formatter, it just outputs the string in the following
153format:
154
155```
156'[{{_timestamp}}][{{_levelString}}]{{_from}}: {{message}}'
157```
158
159Where `_timestamp` is converted to ISO.
160
161#### Accepted Options
162
163* `colorize` <Boolean>: whether or not to add color. False by default.
164
165By default we don't colorize the output, but if you enable the flag this
166formatter will add a bit of color in the level string. Red for bad,
167yellow for warn, blue for info, and white for everything else.
168
169#### Usage
170
171```javascript
172new Cologne.Formatter.Simple({
173 colorize: true
174});
175```
176
177### Example Output
178
179```
180co.log("hello world");
181// -> [2016-01-21T05:50:36.505Z][INFO] Server Logger: hello world
182```
183
184### Cologne.Formatter.Token
185
186The token formatter lets you build strings with simple tokens. When
187instantiating, you can specify a `formatString` to interpolate
188properties from the logObject. The default version looks for tokens
189inside double curly braces like `{{message}}` or `{{_level}}`. If
190you 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
203new Cologne.Formatter.Token({
204 formatString: '[{{_timestamp}}]{{_from}}: {{message}}'
205});
206```
207
208#### ANSI tokens
209
210If you want to add color to your logs, you can use the special \_ansi
211token. It has several options which you can call like `{{_ansi:red}}`
212and `{{_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
233You can create your own formatters by creating an object that responds
234to the `#format()` method, knows how to handle cologne log objects and
235returns a string.
236
237Here's an example of a logger that surrounds a log with sparkles:
238
239```javascript
240var simpleFormatter = {
241 format : function (logObject) {
242 return '✨' + logObject.message + '✨';
243 }
244}
245
246logger.addLogger(new Cologne.Logger.Console({
247 formatter: simpleFormatter
248}));
249```
250
251## The Cologne Log Format
252
253The cologne log format is a JSON based log format, based on the cobalt
254log format, which is inturn based on Graylog's GELF. However, where GELF
255treats all internal fields without a prefix, and all user fields with a
256prefix we do it backwards so it's easier to extend the object with
257metadata from existing objects. Besides, we'll probably write the
258default keys automatically so you shouldn't have to do that extra work.
259
260You could try to build it on your own, but you can use `#buildLog()`
261to 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
277The log levels in cologne correspond to the syslog levels, and the
278levelStrings 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
289This is useful when deciding how to log. You could even have a logger
290filter out unnecessary levels (eg. If you have a reporting logger that
291only 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