UNPKG

9.58 kBMarkdownView Raw
1# Simple Node Logger
2```
3 __ _ _ __ _ __
4/ _(_)_ __ ___ _ __ | | ___ /\ \ \___ __| | ___ / / ___ __ _ __ _ ___ _ __
5\ \| | '_ ` _ \| '_ \| |/ _ \ / \/ / _ \ / _` |/ _ \ / / / _ \ / _` |/ _` |/ _ \ '__|
6_\ \ | | | | | | |_) | | __/ / /\ / (_) | (_| | __/ / /__| (_) | (_| | (_| | __/ |
7\__/_|_| |_| |_| .__/|_|\___| \_\ \/ \___/ \__,_|\___| \____/\___/ \__, |\__, |\___|_|
8 |_| |___/ |___/
9```
10
11[![NPM version](https://badge.fury.io/js/simple-node-logger.svg)](http://badge.fury.io/js/simple-node-logger) [![Build Status](https://travis-ci.org/darrylwest/simple-node-logger.svg?branch=master)](https://travis-ci.org/darrylwest/simple-node-logger) [![Dependency Status](https://david-dm.org/darrylwest/simple-node-logger.svg)](https://david-dm.org/darrylwest/simple-node-logger)
12
13A simple multi-level logger for console, file, and rolling file appenders. Features include:
14
15- levels: trace, debug, info, warn, error and fatal levels (plus all and off)
16- flexible appender/formatters with default to HH:mm:ss.SSS LEVEL message
17- add appenders to send output to console, file, rolling file, etc
18- change log levels on the fly
19- domain and category columns
20- overridable format methods in base appender
21- stats that track counts of all log statements including warn, error, etc
22- ability to configure to emit process error event for central trapping
23
24## Installation
25
26`npm install simple-node-logger --save`
27
28
29## How to use
30```javascript
31// create a stdout console logger
32const log = require('simple-node-logger').createSimpleLogger();
33```
34
35or
36
37```javascript
38// create a stdout and file logger
39const log = require('simple-node-logger').createSimpleLogger('project.log');
40```
41
42or
43
44```javascript
45// create a custom timestamp format for log statements
46const SimpleNodeLogger = require('simple-node-logger'),
47 opts = {
48 logFilePath:'mylogfile.log',
49 timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
50 },
51log = SimpleNodeLogger.createSimpleLogger( opts );
52```
53
54or
55
56```javascript
57// create a file only file logger
58const log = require('simple-node-logger').createSimpleFileLogger('project.log');
59```
60
61or
62
63```javascript
64// create a rolling file logger based on date/time that fires process events
65const opts = {
66 errorEventName:'error',
67 logDirectory:'/mylogfiles', // NOTE: folder must exist and be writable...
68 fileNamePattern:'roll-<DATE>.log',
69 dateFormat:'YYYY.MM.DD'
70};
71const log = require('simple-node-logger').createRollingFileLogger( opts );
72```    
73
74or
75
76```javascript
77// create a log manager
78const manager = require('simple-node-logger').createLogManager();
79
80manager.createConsoleAppender();
81
82const log = manager.createLogger('MyClass');
83// create other logs and appenders...
84```
85
86The first use simply logs to the console. The second logs to the console and to the project.log file. The third create a console logger with a custom timestamp format. The fourth logs to the file only. The fifth creates a rolling file log system in the target log folder. The fifth creates a log manager to enable you to add various appenders with multiple levels and create logs for each module or class.
87
88*See the examples folder for in depth samples...*
89
90## Log Levels
91
92The log levels include the standard set: trace, debug, info, warn, error and fatal. The default level is info. The log level can be set at run-time by doing this:
93
94```javascript
95log.setLevel('warn');
96```
97
98This sets the log level to warn and suppresses debug and info messages.
99
100## Log Statement Formats
101
102### Simple Logger
103
104The default format is HH:mm:ss.SSS LEVEL message. For example, the log message:
105
106```javascript
107log.info('subscription to ', channel, ' accepted at ', new Date().toJSON());
108```
109
110Yields:
111
112`14:14:21.363 INFO subscription to /devchannel accepted at 2014-04-10T14:20:52.938Z`
113
114### Category Logger
115
116If you create a logger with a category name, all log statements will include this category. Typically a category is a class or module name. If you create a logger with the category name 'MyCategory', the log statement would format like this:
117
118`14:14:21.363 INFO MyCategory subscription to /devchannel accepted at 2014-04-10T14:20:52.938Z`
119
120## Appenders
121
122You can create a single logger / log manager and add multiple appenders with different log levels. For example, you can add a console appender that has a log level of warn and a file appender to debug.
123
124_See examples/category-logger.js for an example_.
125
126### Console
127
128Writes to the console. This is the simplest appender typically used for command line applications or for development.
129
130### File
131
132Writes to the specified file. This appender is typically used for services that periodically start and stop or that have a limited number of log statements. An example would be to log just error & fatal messages separate from other logs.
133
134### Rolling File Appender
135
136The rolling file appender offers a full production logger where files roll based on date and time. The minimum roll time is a single hour. A typical application would be a production environment where log files are rolled throughout the day then archived to a separate location.
137
138The rolling file appender requires a valid date format and file name pattern. The filename must contain the key word <DATE> that will be replaced with the formatted date. The configuration must also include a target log directory where the files will be written.
139
140#### Valid Filename Patterns
141
142```
143mylog-<DATE>.log
144ApplicationName.log.<DATE>
145<DATE>.log
146<DATE>
147```
148
149#### Valid Date Formats
150
151Date formats must map to acceptable file names so have more restrictions than typical dates. If you use delimiters, you are restricted to a dash or dot delimiter to separate year, month, day and hour. Valid examples include:
152
153```
154MMDD // simple month day that rolls at midnight (no delimiters)
155YYYY.MM.DD-HH // year month day and hour that can roll up to once per hour
156YYYY-MM-DD.a // year month day and am/pm that rolls twice per day
157YYYY-MMM-DD // year month day where month is the short name (Mar, Apr, etc)
158```
159
160The default format YYYY.MM.DD is used if the format is not supplied.
161
162## Dynamic Configuration
163
164Create a javascript configuration that implements 'readConfig' to return configuration details.
165
166## Examples
167
168The examples folder includes a handful of simple to not so simple cases for console, file, multi-appender, category, etc.
169
170## Customizations
171
172### Appenders
173
174Adding a new appender is as easy as implementing write( logEntry ). The easiest way to implement is by extending the base class AbstractAppender. You may also easily override the formatting, order, etc by overriding or providing your own abstract or concrete appender.
175
176For example, you can extend the AbstractAppender to create a JSON appender by doing this:
177
178```javascript
179 const AbstractAppender = require('simple-node-logger').AbstractAppender;
180
181 const JSONAppender = function() {
182 'use strict';
183 var appender = this;
184
185 var opts = {
186 typeName:'JSONAppender'
187 };
188
189 AbstractAppender.extend( this, opts );
190
191 // format and write all entry/statements
192 this.write = function(entry) {
193 var fields = appender.formatEntry( entry );
194
195 process.stdout.write( JSON.stringify( entry ) + '\n' );
196 };
197    };
198```
199
200### Overrides
201
202#### Appenders
203
204The appenders have formatting messages that can be overridden at the abstract or concrete level. The format methods include:
205
206- formatEntry(entry) - to override all formatting
207- formatMessage(msgList) - to override a list of messages
208- formatDate(value) - custom date, defaults to ISO8601
209- formatObject(value) - custom object, defaults to json for regular objects
210
211#### Logger
212
213It's easy to extend any one of the log methods at the instance level. Here is an example of overriding the error log to send a socket message:
214
215```javascript
216const log = new require('simple-node-logger').createSimpleLogger();
217const socket = openWebSocket();
218
219// override the standard error method to send a socket message
220log.error = function() {
221 var args = Array.prototype.slice.call( arguments ),
222 entry = log.log('error', args);
223
224 // now do something special with the log entry...
225 process.nextTick(function() {
226 socket.send( JSON.stringify( entry ));
227 });
228};
229```
230
231
232## Tests
233
234All unit tests are written in mocha/chai/should and can be run from the command line by doing this:
235
236`make test`
237
238There is also a file watcher that can be invoked with this:
239
240`make watch`
241
242
243## Mocks
244
245Mocks used for testing include MockLogger and MockAppender. Typically you would use MockLogger for unit tests like this:
246
247```javascript
248 const MockLogger = require('simple-node-logger').mocks.MockLogger;
249
250 const log = MockLogger.createLogger('MyCategory');
251
252 log.info('this is a log statement');
253    log.getLogEntries().length.should.equal( 1 );
254```
255
256MockLogger extends Logger and uses MockAppender to capture log entries.
257
258## License
259
260Apache 2.0
261
262## Recent updates...
263
264* 0.93.29: when an Error object is logged, the message and stack trace are sent to log targets
265* 0.93.30: fixed example/category-logger.js and examples/domain-logger.js to not double-log
266* 0.93.31: added thisArg to methods in AbstractAppender to enable proper binding and full override when extending
267
268- - -
269<p><small><em>Copyright © 2014-2017, rain city software | Version 0.93.33</em></small></p>