change approach again

This commit is contained in:
2018-05-09 14:31:22 +02:00
parent 54a933c83a
commit 0686e02b75
2252 changed files with 864743 additions and 270 deletions

201
node_modules/simple-node-logger/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

269
node_modules/simple-node-logger/README.md generated vendored Normal file
View File

@ -0,0 +1,269 @@
# Simple Node Logger
```
__ _ _ __ _ __
/ _(_)_ __ ___ _ __ | | ___ /\ \ \___ __| | ___ / / ___ __ _ __ _ ___ _ __
\ \| | '_ ` _ \| '_ \| |/ _ \ / \/ / _ \ / _` |/ _ \ / / / _ \ / _` |/ _` |/ _ \ '__|
_\ \ | | | | | | |_) | | __/ / /\ / (_) | (_| | __/ / /__| (_) | (_| | (_| | __/ |
\__/_|_| |_| |_| .__/|_|\___| \_\ \/ \___/ \__,_|\___| \____/\___/ \__, |\__, |\___|_|
|_| |___/ |___/
```
[![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)
A simple multi-level logger for console, file, and rolling file appenders. Features include:
- levels: trace, debug, info, warn, error and fatal levels (plus all and off)
- flexible appender/formatters with default to HH:mm:ss.SSS LEVEL message
- add appenders to send output to console, file, rolling file, etc
- change log levels on the fly
- domain and category columns
- overridable format methods in base appender
- stats that track counts of all log statements including warn, error, etc
- ability to configure to emit process error event for central trapping
## Installation
`npm install simple-node-logger --save`
## How to use
```javascript
// create a stdout console logger
const log = require('simple-node-logger').createSimpleLogger();
```
or
```javascript
// create a stdout and file logger
const log = require('simple-node-logger').createSimpleLogger('project.log');
```
or
```javascript
// create a custom timestamp format for log statements
const SimpleNodeLogger = require('simple-node-logger'),
opts = {
logFilePath:'mylogfile.log',
timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
},
log = SimpleNodeLogger.createSimpleLogger( opts );
```
or
```javascript
// create a file only file logger
const log = require('simple-node-logger').createSimpleFileLogger('project.log');
```
or
```javascript
// create a rolling file logger based on date/time that fires process events
const opts = {
errorEventName:'error',
logDirectory:'/mylogfiles', // NOTE: folder must exist and be writable...
fileNamePattern:'roll-<DATE>.log',
dateFormat:'YYYY.MM.DD'
};
const log = require('simple-node-logger').createRollingFileLogger( opts );
```    
or
```javascript
// create a log manager
const manager = require('simple-node-logger').createLogManager();
manager.createConsoleAppender();
const log = manager.createLogger('MyClass');
// create other logs and appenders...
```
The 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.
*See the examples folder for in depth samples...*
## Log Levels
The 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:
```javascript
log.setLevel('warn');
```
This sets the log level to warn and suppresses debug and info messages.
## Log Statement Formats
### Simple Logger
The default format is HH:mm:ss.SSS LEVEL message. For example, the log message:
```javascript
log.info('subscription to ', channel, ' accepted at ', new Date().toJSON());
```
Yields:
`14:14:21.363 INFO subscription to /devchannel accepted at 2014-04-10T14:20:52.938Z`
### Category Logger
If 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:
`14:14:21.363 INFO MyCategory subscription to /devchannel accepted at 2014-04-10T14:20:52.938Z`
## Appenders
You 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.
_See examples/category-logger.js for an example_.
### Console
Writes to the console. This is the simplest appender typically used for command line applications or for development.
### File
Writes 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.
### Rolling File Appender
The 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.
The 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.
#### Valid Filename Patterns
```
mylog-<DATE>.log
ApplicationName.log.<DATE>
<DATE>.log
<DATE>
```
#### Valid Date Formats
Date 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:
```
MMDD // simple month day that rolls at midnight (no delimiters)
YYYY.MM.DD-HH // year month day and hour that can roll up to once per hour
YYYY-MM-DD.a // year month day and am/pm that rolls twice per day
YYYY-MMM-DD // year month day where month is the short name (Mar, Apr, etc)
```
The default format YYYY.MM.DD is used if the format is not supplied.
## Dynamic Configuration
Create a javascript configuration that implements 'readConfig' to return configuration details.
## Examples
The examples folder includes a handful of simple to not so simple cases for console, file, multi-appender, category, etc.
## Customizations
### Appenders
Adding 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.
For example, you can extend the AbstractAppender to create a JSON appender by doing this:
```javascript
const AbstractAppender = require('simple-node-logger').AbstractAppender;
const JSONAppender = function() {
'use strict';
var appender = this;
var opts = {
typeName:'JSONAppender'
};
AbstractAppender.extend( this, opts );
// format and write all entry/statements
this.write = function(entry) {
var fields = appender.formatEntry( entry );
process.stdout.write( JSON.stringify( entry ) + '\n' );
};
   };
```
### Overrides
#### Appenders
The appenders have formatting messages that can be overridden at the abstract or concrete level. The format methods include:
- formatEntry(entry) - to override all formatting
- formatMessage(msgList) - to override a list of messages
- formatDate(value) - custom date, defaults to ISO8601
- formatObject(value) - custom object, defaults to json for regular objects
#### Logger
It'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:
```javascript
const log = new require('simple-node-logger').createSimpleLogger();
const socket = openWebSocket();
// override the standard error method to send a socket message
log.error = function() {
var args = Array.prototype.slice.call( arguments ),
entry = log.log('error', args);
// now do something special with the log entry...
process.nextTick(function() {
socket.send( JSON.stringify( entry ));
});
};
```
## Tests
All unit tests are written in mocha/chai/should and can be run from the command line by doing this:
`make test`
There is also a file watcher that can be invoked with this:
`make watch`
## Mocks
Mocks used for testing include MockLogger and MockAppender. Typically you would use MockLogger for unit tests like this:
```javascript
const MockLogger = require('simple-node-logger').mocks.MockLogger;
const log = MockLogger.createLogger('MyCategory');
log.info('this is a log statement');
   log.getLogEntries().length.should.equal( 1 );
```
MockLogger extends Logger and uses MockAppender to capture log entries.
## License
Apache 2.0
## Recent updates...
* 0.93.29: when an Error object is logged, the message and stack trace are sent to log targets
* 0.93.30: fixed example/category-logger.js and examples/domain-logger.js to not double-log
* 0.93.31: added thisArg to methods in AbstractAppender to enable proper binding and full override when extending
- - -
<p><small><em>Copyright © 2014-2018, rain city software | Version 0.93.37</em></small></p>

18
node_modules/simple-node-logger/index.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
/** darryl.west@raincitysoftware.com **/
module.exports = require('./lib/SimpleLogger');
module.exports.AbstractAppender = require('./lib/AbstractAppender');
module.exports.Logger = require('./lib/Logger');
module.exports.appenders = {
ConsoleAppender:require('./lib/ConsoleAppender'),
FileAppender:require('./lib/FileAppender'),
RollingFileAppender:require('./lib/RollingFileAppender')
};
module.exports.mocks = {
MockAppender:require('./test/mocks/MockAppender'),
MockLogger:require('./test/mocks/MockLogger')
};

155
node_modules/simple-node-logger/lib/AbstractAppender.js generated vendored Normal file
View File

@ -0,0 +1,155 @@
/**
* @class AbstractAppender
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/7/14 5:58 PM
*/
const util = require( 'util' );
const moment = require( 'moment' );
const dash = require( 'lodash' );
const AbstractAppender = function(options) {
'use strict';
const appender = this;
const typeName = options.typeName;
const timestampFormat = options.timestampFormat || 'HH:mm:ss.SSS';
this.separator = options.separator || ' ';
/**
* format the entry and return the field list
*
* @param entry the log entry
* @param thisArg - use this to override the base object
*
* @returns field array
*/
this.formatEntry = function(entry, thisArg) {
const apdr = thisArg || appender;
const fields = [];
if (entry.domain) {
fields.push( entry.domain );
}
fields.push( apdr.formatTimestamp( entry.ts ) );
fields.push( apdr.formatLevel( entry.level ) );
if (entry.category) {
fields.push( entry.category );
}
fields.push( apdr.formatMessage( entry.msg ) );
return fields;
};
/**
* format the message
*
* @param msg the log message
* @param thisArg - use this to override the base object
*
* @returns field array
*/
this.formatMessage = function(msg, thisArg) {
const apdr = thisArg || appender;
if (!msg) {
return '';
}
if (util.isArray( msg )) {
const list = msg.map(function(item) {
if (util.isDate( item )) {
return apdr.formatDate( item );
} else {
return apdr.formatObject( item );
}
});
return list.join('');
} else {
return msg;
}
};
this.formatDate = function(value) {
return value.toJSON();
};
this.formatObject = function(value) {
if (!value) {
return '';
}
if (dash.isObject( value )) {
if (value instanceof Error) {
return [ value.message, value.stack ].join('\n');
}
try {
return JSON.stringify( value );
} catch (ignore) {
return 'json error: ' + value.toString();
}
} else {
var s = value.toString();
if (s === '[object Object]') {
return util.inspect( value );
} else {
return s;
}
}
};
/**
* format the level string by forcing to upper case and padding to 5 chars
*
* @param level
* @returns {string}
*/
this.formatLevel = function(level) {
let str = level.toUpperCase();
if (str.length < 5) {
str += ' ';
}
return str;
};
/**
* format the timestamp to HH:mm:ss.SSS
*
* @param ts the unix milliseconds
* @returns formatted string
*/
this.formatTimestamp = function(ts) {
return moment( ts ).format( timestampFormat );
};
/**
* return the type name of this appender (ConsoleAppender)
*/
this.getTypeName = function() {
return typeName;
};
// constructor tests
if (!typeName) {
throw new Error('appender must be constructed with a type name');
}
};
module.exports = AbstractAppender;
AbstractAppender.extend = function(child, options) {
'use strict';
const parent = new AbstractAppender( options );
dash.extend( child, parent );
return parent;
};

57
node_modules/simple-node-logger/lib/ConsoleAppender.js generated vendored Normal file
View File

@ -0,0 +1,57 @@
/**
* @class ConsoleAppender
* @classdesc ConsoleAppender writes to the console all entries at or above the specified level.
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/6/14 12:02 PM
*/
const Logger = require('./Logger' );
const AbstractAppender = require('./AbstractAppender' );
/*eslint no-console: "off"*/
const ConsoleAppender = function(opts) {
'use strict';
// get a copy of the opts
const options = Object.assign({}, opts);
const appender = this;
const typeName = options.typeName || 'ConsoleAppender';
const writer = options.writer || console.log;
let level = options.level || Logger.STANDARD_LEVELS[0];
let levels = options.levels || Logger.STANDARD_LEVELS;
let currentLevel = levels.indexOf( level );
options.typeName = typeName;
AbstractAppender.extend( this, options );
/**
* default formatter for this appender;
* @param entry
*/
this.formatter = function(entry) {
const fields = appender.formatEntry( entry );
return fields.join( appender.separator );
};
/**
* call formatter then write the entry to the console output
* @param entry - the log entry
*/
this.write = function(entry) {
if (levels.indexOf( entry.level ) >= currentLevel) {
writer( appender.formatter( entry ));
}
};
this.setLevel = function(level) {
const idx = levels.indexOf( level );
if (idx >= 0) {
currentLevel = idx;
}
};
};
module.exports = ConsoleAppender;

91
node_modules/simple-node-logger/lib/FileAppender.js generated vendored Normal file
View File

@ -0,0 +1,91 @@
/**
* @class FileAppender
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/7/14 5:15 PM
*/
const Logger = require('./Logger' );
const AbstractAppender = require('./AbstractAppender' );
const dash = require( 'lodash' );
const path = require( 'path' );
const FileAppender = function(options) {
'use strict';
const appender = this;
const fs = options.fs || require( 'fs' );
const newline = /^win/.test(process.platform) ? '\r\n' : '\n';
const typeName = options.typeName || 'FileAppender';
const autoOpen = dash.isBoolean( options.autoOpen ) ? options.autoOpen : true;
const levels = options.levels || Logger.STANDARD_LEVELS;
let level = options.level || Logger.DEFAULT_LEVEL;
let currentLevel = levels.indexOf( level );
let logFilePath = options.logFilePath;
let writer = options.writer;
options.typeName = typeName;
AbstractAppender.extend( this, options );
/**
* default formatter for this appender;
* @param entry
*/
this.formatter = function(entry) {
const fields = appender.formatEntry( entry );
// add new line (for linux and windows)
fields.push( newline );
return fields.join( appender.separator );
};
/**
* call formatter then write the entry to the console output
* @param entry - the log entry
*/
this.write = function(entry) {
if (levels.indexOf( entry.level ) >= currentLevel) {
writer.write( appender.formatter( entry ) );
}
};
this.setLevel = function(level) {
const idx = levels.indexOf( level );
if (idx >= 0) {
currentLevel = idx;
}
};
// writer is opened on construction
const openWriter = function() {
if (!writer) {
const file = path.normalize( logFilePath );
const opts = {
flags:'a',
encoding:'utf8'
};
writer = fs.createWriteStream( file, opts );
}
};
this.closeWriter = function() {
if (writer) {
writer.end('\n');
}
};
// constructor tests
(function() {
if (!logFilePath) {
throw new Error('appender must be constructed with a log file path');
}
}());
if (autoOpen) {
openWriter();
}
};
module.exports = FileAppender;

184
node_modules/simple-node-logger/lib/Logger.js generated vendored Normal file
View File

@ -0,0 +1,184 @@
/**
* @class Logger
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/5/14 6:28 PM
*/
const Logger = function(options) {
'use strict';
const logger = this,
pid = options.pid || process.pid,
errorEventName = options.errorEventName,
stats = new Map();
let domain = options.domain,
category = options.category,
level = options.level || Logger.DEFAULT_LEVEL,
levels = options.levels || Logger.STANDARD_LEVELS,
currentLevel = levels.indexOf( level ),
appenders = options.appenders || [];
// helper method
const isLevelAt = function(lvl) {
const idx = levels.indexOf( lvl );
return idx >= currentLevel;
};
/**
* log the statement message
*
* @param level the level of this message (label, i.e, info, warn, etc)
* @param msg
*/
this.log = function(level, msg) {
const entry = logger.createEntry( level, msg );
process.nextTick(function() {
// write the message to the appenders...
appenders.forEach(function(appender) {
appender.write( entry );
});
if (level === 'error' && typeof(errorEventName) === 'string') {
process.emit(errorEventName, entry);
}
});
return entry;
};
/**
* create the entry object used to log messages
*
* @param level - info, debug, etc.
* @param messageList - a list of message objects
* @returns then entry object
*/
this.createEntry = function(level, messageList) {
const entry = {};
entry.ts = Date.now();
entry.pid = pid;
if (domain) {
entry.domain = domain;
}
if (category) {
entry.category = category;
}
entry.level = level;
entry.msg = messageList;
return entry;
};
/**
* set the level
*
* @param lvl one of the recognized logger levels
*/
this.setLevel = function(lvl) {
currentLevel = levels.indexOf(lvl);
level = lvl;
appenders.forEach(app => {
app.setLevel( lvl );
});
};
/**
* return the current level string
*/
this.getLevel = function() {
return level;
};
/**
* set the list of appenders
* @param app
*/
this.setAppenders = function(appenderList) {
appenders = appenderList;
};
/**
* add an appender to the list
*
* @param appender - implements write method
*/
this.addAppender = function(appender) {
appenders.push( appender );
};
/**
* remove the appender using the type name
*/
this.removeAppender = function(typeName) {
throw new Error(`remove appender ${typeName} is not implemented yet...`);
};
this.getAppenders = function() {
return appenders;
};
this.isDebug = function() {
return isLevelAt( 'debug' );
};
this.isInfo = function() {
return isLevelAt( 'info' );
};
/**
* return the status map with log counts for each level
*/
this.getStats = function() {
return stats;
};
/**
* return the category name
*/
this.getCategory = function() {
return category;
};
/**
* return the domain name
*/
this.getDomain = function() {
return domain;
};
// now initialize the methods for the standard levels
const init = function() {
levels.forEach(function(lvl) {
stats.set(lvl, 0);
logger[ lvl ] = function() {
stats.set(lvl, stats.get(lvl) + 1);
if (levels.indexOf( lvl ) >= currentLevel) {
const args = Array.prototype.slice.call( arguments );
logger.log( lvl, args );
}
};
});
};
this.__protected = function() {
return {
pid:pid,
domain:domain,
category:category
};
};
init();
};
Logger.STANDARD_LEVELS = [ 'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal' ];
Logger.DEFAULT_LEVEL = 'info';
module.exports = Logger;

View File

@ -0,0 +1,161 @@
/**
* @class RollingFileAppender
*
* roll on size and/or date/time;
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/27/14 9:52 AM
*/
const Logger = require( './Logger' );
const AbstractAppender = require( './AbstractAppender' );
const dash = require( 'lodash' );
const moment = require( 'moment' );
const path = require( 'path' );
const RollingFileAppender = function(options) {
'use strict';
const appender = this;
const fs = options.fs || require( 'fs' );
const newline = /^win/.test(process.platform) ? '\r\n' : '\n';
let typeName = options.typeName,
autoOpen = dash.isBoolean( options.autoOpen ) ? options.autoOpen : true,
logDirectory = options.logDirectory,
fileNamePattern = options.fileNamePattern,
dateFormat = options.dateFormat || 'YYYY.MM.DD',
level = options.level || Logger.DEFAULT_LEVEL,
levels = options.levels || Logger.STANDARD_LEVELS,
currentLevel = levels.indexOf( level ),
currentFile = options.currentFile,
rollTimer,
createInterval = options.createInterval || setInterval,
writers = [];
if (!typeName) {
typeName = options.typeName = 'RollingFileAppender';
}
AbstractAppender.extend( this, options );
const getWriter = function() {
return writers[0];
};
const openWriter = function(fname) {
const filename = fname || appender.createFileName();
const file = path.join( logDirectory, filename );
const opts = {
flags:'a',
encoding:'utf8'
};
let writer = fs.createWriteStream( file, opts );
// make this the current writer...
writers.unshift( writer );
currentFile = file;
// now close the current logger and remove from the writers list
while (writers.length > 1) {
// close the old writer
writer = writers.pop();
writer.removeAllListeners();
writer.end('\n');
}
};
// check once per minute to see if we need to roll
const startRollTimer = function() {
rollTimer = createInterval(function() {
if (appender.checkForRoll()) {
openWriter();
}
}, 60 * 1000);
};
/**
* default formatter for this appender;
* @param entry
*/
this.formatter = function(entry) {
const fields = appender.formatEntry( entry );
fields.push( newline );
return fields.join( appender.separator );
};
/**
* call formatter then write the entry to the console output
* @param entry - the log entry
*/
this.write = function(entry) {
if (levels.indexOf( entry.level ) >= currentLevel) {
const writer = getWriter();
if (writer) {
writer.write( appender.formatter( entry ) );
} else {
/*eslint no-console: "off"*/
console.log( 'no writer...' );
}
}
};
this.checkForRoll = function(now) {
// check to see if the
const fn = appender.createFileName( now );
const current = path.basename( currentFile );
return fn !== current;
};
this.createFileName = function(now) {
let dt;
if (now || now instanceof moment) {
dt = now.format( dateFormat );
} else {
dt = moment().format( dateFormat );
}
return fileNamePattern.replace( /<DATE>/i, dt );
};
this.setLevel = function(level) {
const idx = levels.indexOf( level );
if (idx >= 0) {
currentLevel = idx;
}
};
this.__protected = function() {
return {
openWriter:openWriter,
currentFile:currentFile,
rollTimer:rollTimer,
writers:writers
};
};
// constructor tests
(function() {
if (!logDirectory) {
throw new Error('appender must be constructed with a log directory');
}
if (!fileNamePattern) {
throw new Error('appender must be constructed with a file name pattern');
}
}());
// now validate the date pattern and file format
// date may only contain YMDHAa-.
if (autoOpen) {
openWriter();
startRollTimer();
}
};
module.exports = RollingFileAppender;

325
node_modules/simple-node-logger/lib/SimpleLogger.js generated vendored Normal file
View File

@ -0,0 +1,325 @@
/**
* @class SimpleLogger
*
* @author: darryl.west@raincitysoftware.com
* @created: 2014-07-06
*/
const dash = require( 'lodash' );
const Logger = require('./Logger' );
const ConsoleAppender = require('./ConsoleAppender' );
const FileAppender = require( './FileAppender' );
const RollingFileAppender = require( './RollingFileAppender' );
const SimpleLogger = function(opts) {
'use strict';
const options = Object.assign({}, opts);
const manager = this;
const domain = options.domain;
const appenders = options.appenders || [];
const loggers = options.loggers || [];
let dfltLevel = options.level || Logger.DEFAULT_LEVEL,
loggerConfigFile = options.loggerConfigFile,
refresh = options.refresh,
fs = options.fs || require('fs' ),
createInterval = options.createInterval || setInterval,
minRefresh = options.minRefresh || 10 * 1000,
errorEventName = options.errorEventName;
/**
* create a logger with optional category and level
*
* @param category
* @param level
*/
this.createLogger = function(category, level) {
const opts = Object.prototype.toString.call(category) === '[object String]' ? options : dash.merge({}, options, category);
opts.category = dash.isString(category) ? category : opts.category;
opts.level = level ? level : opts.level || dfltLevel;
opts.appenders = appenders;
if (errorEventName) {
opts.errorEventName = errorEventName;
}
const logger = new Logger( opts );
loggers.push( logger );
return logger;
};
/**
* create the console appender and add it to the appenders list
*
* @param opts - appender settings
* @returns ConsoleAppender -
*/
this.createConsoleAppender = function(opts) {
return manager.addAppender( new ConsoleAppender( Object.assign({}, opts ) ));
};
/**
* create a file appender and add it to the appenders list
*
* @param opts
* @returns a FileAppender object
*/
this.createFileAppender = function(opts) {
if (!opts) {
throw new Error('file appender must be created with log file path set in options');
}
return manager.addAppender( new FileAppender( opts ) );
};
/**
* create a rolling file appender and add it to the appender list
*
* @param opts
* @returns the appender
*/
this.createRollingFileAppender = function( opts ) {
return manager.addAppender( new RollingFileAppender( opts ) );
};
/**
* add the appender to list
*
* @param appender
* @returns the new appender
*/
this.addAppender = function(appender) {
appenders.push( appender );
return appender;
};
this.getAppenders = function() {
return appenders;
};
this.getLoggers = function() {
return loggers;
};
/**
* start the refresh thread; minimum cycle time = 10 seconds...
*/
this.startRefreshThread = function() {
// TODO replace with watcher thread
if (fs.existsSync( loggerConfigFile ) && dash.isNumber( refresh )) {
const t = Math.max( minRefresh, refresh );
createInterval( manager.readConfig, t);
}
};
/**
* set the level of all loggers to the specified level
*
* @param level - one of the know levels
*/
this.setAllLoggerLevels = function(level) {
loggers.forEach(function(logger) {
logger.setLevel( level );
});
};
/**
* read and parse the config file; change settings if required
*/
this.readConfig = function(completeCallback) {
// TODO refactor into configuration delegate to read stats and then process file only if stats change
const callback = (err, buf) => {
if (err) {
/*eslint no-console: "off"*/
console.log( err );
} else {
const conf = JSON.parse( buf.toString() );
if (conf.appenders && conf.appenders.length > 0) {
// find each appender and set the level
conf.appenders.forEach(function(app) {
const level = app.level;
const appender = dash.find( appenders, (item) => {
if (item.getTypeName() === app.typeName && app.level) {
return item;
}
});
if (appender && typeof appender.setLevel === 'function') {
appender.setLevel( level );
}
});
}
if (conf.loggers && conf.loggers.length > 0) {
conf.loggers.forEach(item => {
if (item.category === 'all') {
manager.setAllLoggerLevels( item.level );
}
});
}
}
if (completeCallback) {
return completeCallback( err );
}
};
fs.readFile( loggerConfigFile, callback );
};
this.__protected = function() {
return {
domain:domain,
dfltLevel:dfltLevel,
refresh:refresh,
loggerConfigFile:loggerConfigFile
};
};
};
module.exports = SimpleLogger;
/**
* static convenience method to create a simple console logger; see options for details
*
* @param options - optional, if present then it could be 1) a string or 2) and object. if it's a string it's assumed
* to be the logFilePath; if it's a string or an object with logFilePath property, then a file appender is created.
*
* Valid options:
* - logFilePath : a path to the file appender
* - domain : the logger domain, e.g., machine or site id
* - dfltLevel : the default log level (overrides info level)
* - timestampFormat : the format used for log entries (see moment date formats for all possibilities)
*
* @returns logger
*/
SimpleLogger.createSimpleLogger = function(options) {
'use strict';
let opts;
// if options is a string then it must be the
if (typeof options === 'string') {
opts = {
logFilePath: options
};
} else {
opts = Object.assign( {}, options );
}
const manager = new SimpleLogger(opts);
// pass options in to change date formats, etc
manager.createConsoleAppender( opts );
if (opts.logFilePath) {
manager.createFileAppender( opts );
}
return manager.createLogger();
};
/**
* static convenience method to create a file logger (no console logging);
*
* @param options - if string then it's the logFilePath, else options with the logFilePath
* @returns logger
*/
SimpleLogger.createSimpleFileLogger = function(options) {
'use strict';
if (!options) {
throw new Error('must create file logger with a logFilePath');
}
let opts;
// if options is a string then it must be the
if (typeof options === 'string') {
opts = {
logFilePath: options
};
} else {
opts = Object.assign({}, options );
}
const manager = new SimpleLogger( opts );
manager.createFileAppender( opts );
return manager.createLogger();
};
/**
* create a rolling file logger by passing options to SimpleLogger and Logger. this enables setting
* of domain, category, etc.
*
* @param options
* @returns rolling logger
*/
SimpleLogger.createRollingFileLogger = function(options) {
'use strict';
if (!options) {
throw new Error('createRollingFileLogger requires configuration options for this constructor');
}
var opts;
// read a dynamic config file if available
if (typeof options.readLoggerConfig === 'function') {
opts = options.readLoggerConfig();
opts.readLoggerConfig = options.readLoggerConfig;
} else {
opts = options;
}
var manager = new SimpleLogger( opts );
manager.createRollingFileAppender( opts );
if (opts.refresh && opts.loggerConfigFile) {
process.nextTick( manager.startRefreshThread );
}
return manager.createLogger( opts );
};
/**
* create a log manager
*
* @param options - file or rolling file specs;
*/
SimpleLogger.createLogManager = function(options) {
'use strict';
let opts;
// read a dynamic config file if available
if (options && typeof options.readLoggerConfig === 'function') {
opts = options.readLoggerConfig();
opts.readLoggerConfig = options.readLoggerConfig;
} else {
opts = Object.assign({}, options);
}
var manager = new SimpleLogger( opts );
if (opts.logDirectory && opts.fileNamePattern) {
manager.createRollingFileAppender( opts );
}
// create at least one appender
if (manager.getAppenders().length === 0) {
manager.createConsoleAppender( opts );
}
return manager;
};

69
node_modules/simple-node-logger/package.json generated vendored Normal file
View File

@ -0,0 +1,69 @@
{
"_from": "simple-node-logger@^0.93.33",
"_id": "simple-node-logger@0.93.37",
"_inBundle": false,
"_integrity": "sha512-p80d7uLcNe5U6PU8M0XjXU7YovNFktEttDOXzl+5CIsOlP8eo49IKkw0bXCcW6XwqHV5vyrcCVVxxNyvd4sBpg==",
"_location": "/simple-node-logger",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "simple-node-logger@^0.93.33",
"name": "simple-node-logger",
"escapedName": "simple-node-logger",
"rawSpec": "^0.93.33",
"saveSpec": null,
"fetchSpec": "^0.93.33"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/simple-node-logger/-/simple-node-logger-0.93.37.tgz",
"_shasum": "4e1235917b3b4a8d6cc10e0208d157189afb2106",
"_spec": "simple-node-logger@^0.93.33",
"_where": "/home/wn/workspace-node/homepage",
"author": {
"name": "darryl.west@raincitysoftware.com"
},
"bugs": {
"url": "https://github.com/darrylwest/simple-node-logger/issues"
},
"bundleDependencies": false,
"dependencies": {
"lodash": "^4.17.2",
"moment": "^2.20.1"
},
"deprecated": false,
"description": "A node console and file logger suitable for small, medium and large production projects.",
"devDependencies": {
"chai": "^3.5.0",
"eslint": "^3.19.0",
"mocha": "^3.2.0",
"random-fixture-data": "^2.0.17"
},
"files": [
"index.js",
"lib/",
"test/mocks"
],
"homepage": "https://github.com/darrylwest/simple-node-logger",
"keywords": [
"log",
"logger",
"multi-appender",
"file logger",
"rolling file logger",
"console logger"
],
"license": "Apache-2.0",
"main": "index.js",
"name": "simple-node-logger",
"repository": {
"type": "git",
"url": "git://github.com/darrylwest/simple-node-logger.git"
},
"scripts": {
"test": "make test"
},
"version": "0.93.37"
}

View File

@ -0,0 +1,35 @@
/**
* @class MockAppender
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/6/14 8:41 AM
*/
const MockAppender = function() {
'use strict';
const Logger = require('../../lib/Logger' );
let level = Logger.DEFAULT_LEVEL;
let levels = Logger.STANDARD_LEVELS;
let currentLevel = levels.indexOf( level );
let appender = this;
this.entries = [];
this.setLevel = function(level) {
let idx = levels.indexOf( level );
if (idx >= 0) {
currentLevel = idx;
}
};
this.getCurrentLevel = function() {
return currentLevel;
};
this.write = function(entry) {
appender.entries.push( entry );
};
};
module.exports = MockAppender;

View File

@ -0,0 +1,52 @@
/**
* @class MockLogger
*
* @author: darryl.west@raincitysoftware.com
* @created: 7/8/14 5:16 PM
*/
const dash = require('lodash' ),
Logger = require('../../lib/Logger' ),
MockAppender = require('./MockAppender');
const MockLogger = function(options) {
'use strict';
const opts = Object.assign({}, options);
// const mock = this;
const appender = new MockAppender();
// set these if not passed in
if (!opts.pid) {
opts.pid = 'test12345';
}
if (!opts.appenders) {
opts.appenders = [ appender ];
}
if (!opts.level) {
opts.level = 'trace';
}
dash.extend( this, new Logger(opts) );
this.getLogEntries = function() {
return appender.entries;
};
};
MockLogger.createLogger = function(category, level) {
'use strict';
const opts = {};
if (category) {
opts.category = category;
}
if (level) {
opts.level = level;
}
return new MockLogger( opts );
};
module.exports = MockLogger;