fixed all lint errors except ones which require refactoring of code
This commit is contained in:
parent
f998d7e81a
commit
5d6f00eda4
@ -1,9 +1,10 @@
|
|||||||
var streams = require('../streams'),
|
"use strict";
|
||||||
layouts = require('../layouts'),
|
var streams = require('../streams')
|
||||||
path = require('path'),
|
, layouts = require('../layouts')
|
||||||
os = require('os'),
|
, path = require('path')
|
||||||
eol = os.EOL || '\n',
|
, os = require('os')
|
||||||
openFiles = [];
|
, eol = os.EOL || '\n'
|
||||||
|
, openFiles = [];
|
||||||
|
|
||||||
//close open files on process exit.
|
//close open files on process exit.
|
||||||
process.on('exit', function() {
|
process.on('exit', function() {
|
||||||
@ -22,7 +23,11 @@ process.on('exit', function() {
|
|||||||
function appender(filename, pattern, alwaysIncludePattern, layout) {
|
function appender(filename, pattern, alwaysIncludePattern, layout) {
|
||||||
layout = layout || layouts.basicLayout;
|
layout = layout || layouts.basicLayout;
|
||||||
|
|
||||||
var logFile = new streams.DateRollingFileStream(filename, pattern, { alwaysIncludePattern: alwaysIncludePattern });
|
var logFile = new streams.DateRollingFileStream(
|
||||||
|
filename,
|
||||||
|
pattern,
|
||||||
|
{ alwaysIncludePattern: alwaysIncludePattern }
|
||||||
|
);
|
||||||
openFiles.push(logFile);
|
openFiles.push(logFile);
|
||||||
|
|
||||||
return function(logEvent) {
|
return function(logEvent) {
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
"use strict";
|
||||||
var layouts = require('../layouts')
|
var layouts = require('../layouts')
|
||||||
, path = require('path')
|
, path = require('path')
|
||||||
, fs = require('fs')
|
, fs = require('fs')
|
||||||
@ -17,9 +18,12 @@ process.on('exit', function() {
|
|||||||
* File Appender writing the logs to a text file. Supports rolling of logs by size.
|
* File Appender writing the logs to a text file. Supports rolling of logs by size.
|
||||||
*
|
*
|
||||||
* @param file file log messages will be written to
|
* @param file file log messages will be written to
|
||||||
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
|
* @param layout a function that takes a logevent and returns a string
|
||||||
* @param logSize - the maximum size (in bytes) for a log file, if not provided then logs won't be rotated.
|
* (defaults to basicLayout).
|
||||||
* @param numBackups - the number of log files to keep after logSize has been reached (default 5)
|
* @param logSize - the maximum size (in bytes) for a log file,
|
||||||
|
* if not provided then logs won't be rotated.
|
||||||
|
* @param numBackups - the number of log files to keep after logSize
|
||||||
|
* has been reached (default 5)
|
||||||
*/
|
*/
|
||||||
function fileAppender (file, layout, logSize, numBackups) {
|
function fileAppender (file, layout, logSize, numBackups) {
|
||||||
var bytesWritten = 0;
|
var bytesWritten = 0;
|
||||||
@ -38,7 +42,12 @@ function fileAppender (file, layout, logSize, numBackups) {
|
|||||||
numFiles
|
numFiles
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
stream = fs.createWriteStream(file, { encoding: "utf8", mode: 0644, flags: 'a' });
|
stream = fs.createWriteStream(
|
||||||
|
file,
|
||||||
|
{ encoding: "utf8",
|
||||||
|
mode: parseInt('0644', 8),
|
||||||
|
flags: 'a' }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
stream.on("error", function (err) {
|
stream.on("error", function (err) {
|
||||||
console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err);
|
console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err);
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
"use strict";
|
||||||
var zlib = require('zlib');
|
var zlib = require('zlib');
|
||||||
var layouts = require('../layouts');
|
var layouts = require('../layouts');
|
||||||
var levels = require('../levels');
|
var levels = require('../levels');
|
||||||
@ -23,6 +24,13 @@ levelMapping[levels.WARN] = LOG_WARNING;
|
|||||||
levelMapping[levels.ERROR] = LOG_ERR;
|
levelMapping[levels.ERROR] = LOG_ERR;
|
||||||
levelMapping[levels.FATAL] = LOG_CRIT;
|
levelMapping[levels.FATAL] = LOG_CRIT;
|
||||||
|
|
||||||
|
var debug;
|
||||||
|
if (process.env.NODE_DEBUG && /\blog4js\b/.test(process.env.NODE_DEBUG)) {
|
||||||
|
debug = function(message) { console.error('LOG4JS: (GELF Appender) %s', message); };
|
||||||
|
} else {
|
||||||
|
debug = function() { };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GELF appender that supports sending UDP packets to a GELF compatible server such as Graylog
|
* GELF appender that supports sending UDP packets to a GELF compatible server such as Graylog
|
||||||
*
|
*
|
||||||
@ -72,7 +80,7 @@ function gelfAppender (layout, host, port, hostname, facility) {
|
|||||||
console.error(err.stack);
|
console.error(err.stack);
|
||||||
} else {
|
} else {
|
||||||
if (packet.length > 8192) {
|
if (packet.length > 8192) {
|
||||||
util.debug("Message packet length (" + packet.length + ") is larger than 8k. Not sending");
|
debug("Message packet length (" + packet.length + ") is larger than 8k. Not sending");
|
||||||
} else {
|
} else {
|
||||||
sendPacket(packet);
|
sendPacket(packet);
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
var log4js = require('../log4js');
|
"use strict";
|
||||||
var layouts = require('../layouts');
|
var log4js = require('../log4js')
|
||||||
var Hook = require('hook.io').Hook;
|
, layouts = require('../layouts')
|
||||||
var util = require('util');
|
, Hook = require('hook.io').Hook
|
||||||
|
, util = require('util');
|
||||||
|
|
||||||
var Logger = function createLogger(options) {
|
var Logger = function createLogger(options) {
|
||||||
var self = this;
|
var self = this;
|
||||||
@ -13,7 +14,7 @@ var Logger = function createLogger(options) {
|
|||||||
actualAppender(loggingEvent);
|
actualAppender(loggingEvent);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
util.inherits(Logger, Hook);
|
util.inherits(Logger, Hook);
|
||||||
|
|
||||||
function deserializeLoggingEvent(loggingEvent) {
|
function deserializeLoggingEvent(loggingEvent) {
|
||||||
@ -42,7 +43,7 @@ function getBufferedHook(hook, eventName) {
|
|||||||
hook.on('hook::ready', function emptyBuffer() {
|
hook.on('hook::ready', function emptyBuffer() {
|
||||||
hookBuffer.forEach(function logBufferItem(loggingEvent) {
|
hookBuffer.forEach(function logBufferItem(loggingEvent) {
|
||||||
hook.emit(eventName, loggingEvent);
|
hook.emit(eventName, loggingEvent);
|
||||||
})
|
});
|
||||||
hookReady = true;
|
hookReady = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -52,7 +53,7 @@ function getBufferedHook(hook, eventName) {
|
|||||||
} else {
|
} else {
|
||||||
hookBuffer.push(loggingEvent);
|
hookBuffer.push(loggingEvent);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function createAppender(hookioOptions) {
|
function createAppender(hookioOptions) {
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
var levels = require('../levels');
|
"use strict";
|
||||||
var log4js = require('../log4js');
|
var levels = require('../levels')
|
||||||
|
, log4js = require('../log4js');
|
||||||
|
|
||||||
function logLevelFilter (levelString, appender) {
|
function logLevelFilter (levelString, appender) {
|
||||||
var level = levels.toLevel(levelString);
|
var level = levels.toLevel(levelString);
|
||||||
@ -7,7 +8,7 @@ function logLevelFilter (levelString, appender) {
|
|||||||
if (logEvent.level.isGreaterThanOrEqualTo(level)) {
|
if (logEvent.level.isGreaterThanOrEqualTo(level)) {
|
||||||
appender(logEvent);
|
appender(logEvent);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function configure(config) {
|
function configure(config) {
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
var log4js = require('../log4js'),
|
"use strict";
|
||||||
net = require('net'),
|
var log4js = require('../log4js')
|
||||||
END_MSG = '__LOG4JS__';
|
, net = require('net')
|
||||||
|
, END_MSG = '__LOG4JS__';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a server, listening on config.loggerPort, config.loggerHost.
|
* Creates a server, listening on config.loggerPort, config.loggerHost.
|
||||||
|
@ -1,14 +1,17 @@
|
|||||||
var layouts = require("../layouts"),
|
"use strict";
|
||||||
mailer = require("nodemailer"),
|
var layouts = require("../layouts")
|
||||||
os = require('os');
|
, mailer = require("nodemailer")
|
||||||
|
, os = require('os');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SMTP Appender. Sends logging events using SMTP protocol.
|
* SMTP Appender. Sends logging events using SMTP protocol.
|
||||||
* It can either send an email on each event or group several logging events gathered during specified interval.
|
* It can either send an email on each event or group several
|
||||||
|
* logging events gathered during specified interval.
|
||||||
*
|
*
|
||||||
* @param config appender configuration data
|
* @param config appender configuration data
|
||||||
|
* config.sendInterval time between log emails (in seconds), if 0
|
||||||
|
* then every event sends an email
|
||||||
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
|
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
|
||||||
* all events are buffered and sent in one email during this time; if 0 than every event sends an email
|
|
||||||
*/
|
*/
|
||||||
function smtpAppender(config, layout) {
|
function smtpAppender(config, layout) {
|
||||||
layout = layout || layouts.basicLayout;
|
layout = layout || layouts.basicLayout;
|
||||||
@ -19,7 +22,7 @@ function smtpAppender(config, layout) {
|
|||||||
var sendTimer;
|
var sendTimer;
|
||||||
|
|
||||||
function sendBuffer() {
|
function sendBuffer() {
|
||||||
if (logEventBuffer.length == 0) {
|
if (logEventBuffer.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,9 @@
|
|||||||
|
"use strict";
|
||||||
var levels = require("./levels");
|
var levels = require("./levels");
|
||||||
|
var DEFAULT_FORMAT = ':remote-addr - -' +
|
||||||
|
' ":method :url HTTP/:http-version"' +
|
||||||
|
' :status :content-length ":referrer"' +
|
||||||
|
' ":user-agent"';
|
||||||
/**
|
/**
|
||||||
* Log requests with the given `options` or a `format` string.
|
* Log requests with the given `options` or a `format` string.
|
||||||
*
|
*
|
||||||
@ -37,11 +42,10 @@ var levels = require("./levels");
|
|||||||
|
|
||||||
var thislogger = logger4js
|
var thislogger = logger4js
|
||||||
, level = levels.toLevel(options.level, levels.INFO)
|
, level = levels.toLevel(options.level, levels.INFO)
|
||||||
, fmt = options.format || ':remote-addr - - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"'
|
, fmt = options.format || DEFAULT_FORMAT
|
||||||
, nolog = options.nolog ? createNoLogCondition(options.nolog) : null;
|
, nolog = options.nolog ? createNoLogCondition(options.nolog) : null;
|
||||||
|
|
||||||
return function (req, res, next) {
|
return function (req, res, next) {
|
||||||
|
|
||||||
// mount safety
|
// mount safety
|
||||||
if (req._logging) return next();
|
if (req._logging) return next();
|
||||||
|
|
||||||
@ -49,7 +53,7 @@ var levels = require("./levels");
|
|||||||
if (nolog && nolog.test(req.originalUrl)) return next();
|
if (nolog && nolog.test(req.originalUrl)) return next();
|
||||||
if (thislogger.isLevelEnabled(level) || options.level === 'auto') {
|
if (thislogger.isLevelEnabled(level) || options.level === 'auto') {
|
||||||
|
|
||||||
var start = +new Date
|
var start = new Date()
|
||||||
, statusCode
|
, statusCode
|
||||||
, writeHead = res.writeHead
|
, writeHead = res.writeHead
|
||||||
, end = res.end
|
, end = res.end
|
||||||
@ -71,7 +75,7 @@ var levels = require("./levels");
|
|||||||
if(code >= 300) level = levels.WARN;
|
if(code >= 300) level = levels.WARN;
|
||||||
if(code >= 400) level = levels.ERROR;
|
if(code >= 400) level = levels.ERROR;
|
||||||
} else {
|
} else {
|
||||||
level = levels.toLevel(options.level, levels.INFO)
|
level = levels.toLevel(options.level, levels.INFO);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -79,7 +83,7 @@ var levels = require("./levels");
|
|||||||
res.end = function(chunk, encoding) {
|
res.end = function(chunk, encoding) {
|
||||||
res.end = end;
|
res.end = end;
|
||||||
res.end(chunk, encoding);
|
res.end(chunk, encoding);
|
||||||
res.responseTime = +new Date - start;
|
res.responseTime = new Date() - start;
|
||||||
if (thislogger.isLevelEnabled(level)) {
|
if (thislogger.isLevelEnabled(level)) {
|
||||||
if (typeof fmt === 'function') {
|
if (typeof fmt === 'function') {
|
||||||
var line = fmt(req, res, function(str){ return format(str, req, res); });
|
var line = fmt(req, res, function(str){ return format(str, req, res); });
|
||||||
@ -113,15 +117,24 @@ var levels = require("./levels");
|
|||||||
.replace(':status', res.__statusCode || res.statusCode)
|
.replace(':status', res.__statusCode || res.statusCode)
|
||||||
.replace(':response-time', res.responseTime)
|
.replace(':response-time', res.responseTime)
|
||||||
.replace(':date', new Date().toUTCString())
|
.replace(':date', new Date().toUTCString())
|
||||||
.replace(':referrer', req.headers['referer'] || req.headers['referrer'] || '')
|
.replace(':referrer', req.headers.referer || req.headers.referrer || '')
|
||||||
.replace(':http-version', req.httpVersionMajor + '.' + req.httpVersionMinor)
|
.replace(':http-version', req.httpVersionMajor + '.' + req.httpVersionMinor)
|
||||||
.replace(':remote-addr', req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress)))
|
.replace(
|
||||||
|
':remote-addr',
|
||||||
|
req.socket &&
|
||||||
|
(req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress))
|
||||||
|
)
|
||||||
.replace(':user-agent', req.headers['user-agent'] || '')
|
.replace(':user-agent', req.headers['user-agent'] || '')
|
||||||
.replace(':content-length', (res._headers && res._headers['content-length']) || (res.__headers && res.__headers['Content-Length']) || '-')
|
.replace(
|
||||||
|
':content-length',
|
||||||
|
(res._headers && res._headers['content-length']) ||
|
||||||
|
(res.__headers && res.__headers['Content-Length']) ||
|
||||||
|
'-'
|
||||||
|
)
|
||||||
.replace(/:req\[([^\]]+)\]/g, function(_, field){ return req.headers[field.toLowerCase()]; })
|
.replace(/:req\[([^\]]+)\]/g, function(_, field){ return req.headers[field.toLowerCase()]; })
|
||||||
.replace(/:res\[([^\]]+)\]/g, function(_, field){
|
.replace(/:res\[([^\]]+)\]/g, function(_, field){
|
||||||
return res._headers
|
return res._headers ?
|
||||||
? (res._headers[field.toLowerCase()] || res.__headers[field])
|
(res._headers[field.toLowerCase()] || res.__headers[field])
|
||||||
: (res.__headers && res.__headers[field]);
|
: (res.__headers && res.__headers[field]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -141,8 +154,10 @@ var levels = require("./levels");
|
|||||||
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga
|
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga
|
||||||
* LOGGING http://example.com/hoge.agif
|
* LOGGING http://example.com/hoge.agif
|
||||||
* 1.2 in "\\.gif|\\.jpg$"
|
* 1.2 in "\\.gif|\\.jpg$"
|
||||||
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga
|
* NOT LOGGING http://example.com/hoge.gif and
|
||||||
* LOGGING http://example.com/hoge.agif, http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge
|
* http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga
|
||||||
|
* LOGGING http://example.com/hoge.agif,
|
||||||
|
* http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge
|
||||||
* 1.3 in "\\.(gif|jpe?g|png)$"
|
* 1.3 in "\\.(gif|jpe?g|png)$"
|
||||||
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg
|
* NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg
|
||||||
* LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3
|
* LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3
|
||||||
@ -158,19 +173,21 @@ var levels = require("./levels");
|
|||||||
type = type || '';
|
type = type || '';
|
||||||
|
|
||||||
if (nolog instanceof RegExp) {
|
if (nolog instanceof RegExp) {
|
||||||
if(type === 'string')
|
if (type === 'string') {
|
||||||
return nolog.source;
|
return nolog.source;
|
||||||
|
}
|
||||||
return nolog;
|
return nolog;
|
||||||
} else if (typeof nolog === 'string') {
|
} else if (typeof nolog === 'string') {
|
||||||
if(type === 'string')
|
if (type === 'string') {
|
||||||
return nolog;
|
return nolog;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return new RegExp(nolog);
|
return new RegExp(nolog);
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
} else if (nolog instanceof Array) {
|
} else if (nolog instanceof Array) {
|
||||||
var regexps = nolog.map(function(o){ return createNoLogCondition(o, 'string')});
|
var regexps = nolog.map(function(o){ return createNoLogCondition(o, 'string'); });
|
||||||
return new RegExp(regexps.join('|'));
|
return new RegExp(regexps.join('|'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,28 +1,29 @@
|
|||||||
|
"use strict";
|
||||||
var dateFormat = require('./date_format')
|
var dateFormat = require('./date_format')
|
||||||
, os = require('os')
|
, os = require('os')
|
||||||
, eol = os.EOL || '\n'
|
, eol = os.EOL || '\n'
|
||||||
, util = require('util')
|
, util = require('util')
|
||||||
, replacementRegExp = /%[sdj]/g
|
, replacementRegExp = /%[sdj]/g
|
||||||
, layoutMakers = {
|
, layoutMakers = {
|
||||||
"messagePassThrough": function() { return messagePassThroughLayout; }
|
"messagePassThrough": function() { return messagePassThroughLayout; },
|
||||||
, "basic": function() { return basicLayout; }
|
"basic": function() { return basicLayout; },
|
||||||
, "colored": function() { return colouredLayout; }
|
"colored": function() { return colouredLayout; },
|
||||||
, "coloured": function() { return colouredLayout; }
|
"coloured": function() { return colouredLayout; },
|
||||||
, "pattern": function (config) {
|
"pattern": function (config) {
|
||||||
var pattern = config.pattern || undefined;
|
var pattern = config.pattern || undefined;
|
||||||
var tokens = config.tokens || undefined;
|
var tokens = config.tokens || undefined;
|
||||||
return patternLayout(pattern, tokens);
|
return patternLayout(pattern, tokens);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
, colours = {
|
, colours = {
|
||||||
ALL: "grey"
|
ALL: "grey",
|
||||||
, TRACE: "blue"
|
TRACE: "blue",
|
||||||
, DEBUG: "cyan"
|
DEBUG: "cyan",
|
||||||
, INFO: "green"
|
INFO: "green",
|
||||||
, WARN: "yellow"
|
WARN: "yellow",
|
||||||
, ERROR: "red"
|
ERROR: "red",
|
||||||
, FATAL: "magenta"
|
FATAL: "magenta",
|
||||||
, OFF: "grey"
|
OFF: "grey"
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatLogData(logData) {
|
function formatLogData(logData) {
|
||||||
@ -33,12 +34,15 @@ function formatLogData(logData) {
|
|||||||
if (typeof format === "string") {
|
if (typeof format === "string") {
|
||||||
output = format.replace(replacementRegExp, function(match) {
|
output = format.replace(replacementRegExp, function(match) {
|
||||||
switch (match) {
|
switch (match) {
|
||||||
case "%s": return new String(data.shift());
|
case "%s":
|
||||||
case "%d": return new Number(data.shift());
|
return data.shift().toString();
|
||||||
case "%j": return JSON.stringify(data.shift());
|
case "%d":
|
||||||
|
return new Number(data.shift());
|
||||||
|
case "%j":
|
||||||
|
return JSON.stringify(data.shift());
|
||||||
default:
|
default:
|
||||||
return match;
|
return match;
|
||||||
};
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
//put it back, it's not a format string
|
//put it back, it's not a format string
|
||||||
@ -78,10 +82,10 @@ var styles = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function colorizeStart(style) {
|
function colorizeStart(style) {
|
||||||
return style ? '\033[' + styles[style][0] + 'm' : '';
|
return style ? '\x1B[' + styles[style][0] + 'm' : '';
|
||||||
}
|
}
|
||||||
function colorizeEnd(style) {
|
function colorizeEnd(style) {
|
||||||
return style ? '\033[' + styles[style][1] + 'm' : '';
|
return style ? '\x1B[' + styles[style][1] + 'm' : '';
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Taken from masylum's fork (https://github.com/masylum/log4js-node)
|
* Taken from masylum's fork (https://github.com/masylum/log4js-node)
|
||||||
@ -121,7 +125,10 @@ function basicLayout (loggingEvent) {
|
|||||||
* same as basicLayout, but with colours.
|
* same as basicLayout, but with colours.
|
||||||
*/
|
*/
|
||||||
function colouredLayout (loggingEvent) {
|
function colouredLayout (loggingEvent) {
|
||||||
return timestampLevelAndCategory(loggingEvent, colours[loggingEvent.level.toString()]) + formatLogData(loggingEvent.data);
|
return timestampLevelAndCategory(
|
||||||
|
loggingEvent,
|
||||||
|
colours[loggingEvent.level.toString()]
|
||||||
|
) + formatLogData(loggingEvent.data);
|
||||||
}
|
}
|
||||||
|
|
||||||
function messagePassThroughLayout (loggingEvent) {
|
function messagePassThroughLayout (loggingEvent) {
|
||||||
@ -283,15 +290,15 @@ function patternLayout (pattern, tokens) {
|
|||||||
return formattedString;
|
return formattedString;
|
||||||
};
|
};
|
||||||
|
|
||||||
};
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
basicLayout: basicLayout
|
basicLayout: basicLayout,
|
||||||
, messagePassThroughLayout: messagePassThroughLayout
|
messagePassThroughLayout: messagePassThroughLayout,
|
||||||
, patternLayout: patternLayout
|
patternLayout: patternLayout,
|
||||||
, colouredLayout: colouredLayout
|
colouredLayout: colouredLayout,
|
||||||
, coloredLayout: colouredLayout
|
coloredLayout: colouredLayout,
|
||||||
, layout: function(name, config) {
|
layout: function(name, config) {
|
||||||
return layoutMakers[name] && layoutMakers[name](config);
|
return layoutMakers[name] && layoutMakers[name](config);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
"use strict";
|
||||||
/*
|
/*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -12,8 +13,6 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/*jsl:option explicit*/
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @fileoverview log4js is a library to log in JavaScript in similar manner
|
* @fileoverview log4js is a library to log in JavaScript in similar manner
|
||||||
* than in log4j for Java. The API should be nearly the same.
|
* than in log4j for Java. The API should be nearly the same.
|
||||||
@ -72,7 +71,7 @@ var events = require('events')
|
|||||||
function getLogger (categoryName) {
|
function getLogger (categoryName) {
|
||||||
|
|
||||||
// Use default logger if categoryName is not specified or invalid
|
// Use default logger if categoryName is not specified or invalid
|
||||||
if (!(typeof categoryName == "string")) {
|
if (typeof categoryName !== "string") {
|
||||||
categoryName = Logger.DEFAULT_CATEGORY;
|
categoryName = Logger.DEFAULT_CATEGORY;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,7 +102,7 @@ function getLogger (categoryName) {
|
|||||||
function addAppender () {
|
function addAppender () {
|
||||||
var args = Array.prototype.slice.call(arguments);
|
var args = Array.prototype.slice.call(arguments);
|
||||||
var appender = args.shift();
|
var appender = args.shift();
|
||||||
if (args.length == 0 || args[0] === undefined) {
|
if (args.length === 0 || args[0] === undefined) {
|
||||||
args = [ ALL_CATEGORIES ];
|
args = [ ALL_CATEGORIES ];
|
||||||
}
|
}
|
||||||
//argument may already be an array
|
//argument may already be an array
|
||||||
@ -181,8 +180,12 @@ function getDefaultLogger () {
|
|||||||
var configState = {};
|
var configState = {};
|
||||||
|
|
||||||
function loadConfigurationFile(filename) {
|
function loadConfigurationFile(filename) {
|
||||||
if (filename && (!configState.lastFilename || filename !== configState.lastFilename ||
|
if (filename &&
|
||||||
!configState.lastMTime || fs.statSync(filename).mtime !== configState.lastMTime)) {
|
(!configState.lastFilename ||
|
||||||
|
filename !== configState.lastFilename ||
|
||||||
|
!configState.lastMTime ||
|
||||||
|
fs.statSync(filename).mtime !== configState.lastMTime)
|
||||||
|
) {
|
||||||
configState.lastFilename = filename;
|
configState.lastFilename = filename;
|
||||||
configState.lastMTime = fs.statSync(filename).mtime;
|
configState.lastMTime = fs.statSync(filename).mtime;
|
||||||
return JSON.parse(fs.readFileSync(filename, "utf8"));
|
return JSON.parse(fs.readFileSync(filename, "utf8"));
|
||||||
@ -202,7 +205,10 @@ function configureOnceOff(config, options) {
|
|||||||
restoreConsole();
|
restoreConsole();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error("Problem reading log4js config " + util.inspect(config) + ". Error was \"" + e.message + "\" ("+e.stack+")");
|
throw new Error(
|
||||||
|
"Problem reading log4js config " + util.inspect(config) +
|
||||||
|
". Error was \"" + e.message + "\" (" + e.stack + ")"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -250,7 +256,9 @@ function configure(configurationFileOrObject, options) {
|
|||||||
config = loadConfigurationFile(config) || defaultConfig;
|
config = loadConfigurationFile(config) || defaultConfig;
|
||||||
} else {
|
} else {
|
||||||
if (options.reloadSecs) {
|
if (options.reloadSecs) {
|
||||||
getLogger('log4js').warn('Ignoring configuration reload parameter for "object" configuration.');
|
getLogger('log4js').warn(
|
||||||
|
'Ignoring configuration reload parameter for "object" configuration.'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
configureOnceOff(config, options);
|
configureOnceOff(config, options);
|
||||||
@ -268,7 +276,7 @@ function replaceConsole(logger) {
|
|||||||
function replaceWith(fn) {
|
function replaceWith(fn) {
|
||||||
return function() {
|
return function() {
|
||||||
fn.apply(logger, arguments);
|
fn.apply(logger, arguments);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
logger = logger || getLogger("console");
|
logger = logger || getLogger("console");
|
||||||
['log','debug','info','warn','error'].forEach(function (item) {
|
['log','debug','info','warn','error'].forEach(function (item) {
|
||||||
|
@ -1,7 +1,10 @@
|
|||||||
|
"use strict";
|
||||||
// This test shows unexpected behaviour for log4js.configure() in log4js-node@0.4.3 and earlier:
|
// This test shows unexpected behaviour for log4js.configure() in log4js-node@0.4.3 and earlier:
|
||||||
// 1) log4js.configure(), log4js.configure(null), log4js.configure({}), log4js.configure(<some object with no levels prop>)
|
// 1) log4js.configure(), log4js.configure(null),
|
||||||
|
// log4js.configure({}), log4js.configure(<some object with no levels prop>)
|
||||||
// all set all loggers levels to trace, even if they were previously set to something else.
|
// all set all loggers levels to trace, even if they were previously set to something else.
|
||||||
// 2) log4js.configure({levels:{}}), log4js.configure({levels: {foo: bar}}) leaves previously set logger levels intact.
|
// 2) log4js.configure({levels:{}}), log4js.configure({levels: {foo:
|
||||||
|
// bar}}) leaves previously set logger levels intact.
|
||||||
//
|
//
|
||||||
|
|
||||||
// Basic set up
|
// Basic set up
|
||||||
@ -28,7 +31,7 @@ var configs = {
|
|||||||
'has empty levels': {levels: {}},
|
'has empty levels': {levels: {}},
|
||||||
'has random levels': {levels: {foo: 'bar'}},
|
'has random levels': {levels: {foo: 'bar'}},
|
||||||
'has some valid levels': {levels: {A: 'INFO'}}
|
'has some valid levels': {levels: {A: 'INFO'}}
|
||||||
}
|
};
|
||||||
|
|
||||||
// Set up the basic vows batches for this test
|
// Set up the basic vows batches for this test
|
||||||
var batches = [];
|
var batches = [];
|
||||||
@ -60,13 +63,14 @@ function getTopLevelContext(nop, configToTest, name) {
|
|||||||
}
|
}
|
||||||
return log4js;
|
return log4js;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
showProgress('Populating batch object...');
|
showProgress('Populating batch object...');
|
||||||
|
|
||||||
// Populating the batches programmatically,
|
// Populating the batches programmatically, as there are
|
||||||
// as there are (configs.length x strLevels.length x strLevels.length) = 324 possible test combinations
|
// (configs.length x strLevels.length x strLevels.length) = 324
|
||||||
|
// possible test combinations
|
||||||
for (var cfg in configs) {
|
for (var cfg in configs) {
|
||||||
var configToTest = configs[cfg];
|
var configToTest = configs[cfg];
|
||||||
var nop = configToTest === 'nop';
|
var nop = configToTest === 'nop';
|
||||||
@ -84,43 +88,73 @@ for (var cfg in configs) {
|
|||||||
batch[context]= getTopLevelContext(nop, configToTest, context);
|
batch[context]= getTopLevelContext(nop, configToTest, context);
|
||||||
batches.push(batch);
|
batches.push(batch);
|
||||||
|
|
||||||
// each top-level context has strLevels sub-contexts, one per logger which has set to a specific level in the top-level context's topic
|
// each top-level context has strLevels sub-contexts, one per logger
|
||||||
|
// which has set to a specific level in the top-level context's topic
|
||||||
strLevels.forEach(function (baseLevel) {
|
strLevels.forEach(function (baseLevel) {
|
||||||
var baseLevelSubContext = 'and checking the logger whose level was set to '+baseLevel ;
|
var baseLevelSubContext = 'and checking the logger whose level was set to '+baseLevel ;
|
||||||
batch[context][baseLevelSubContext] = {topic: baseLevel};
|
var subContext = { topic: baseLevel };
|
||||||
|
batch[context][baseLevelSubContext] = subContext;
|
||||||
|
|
||||||
// each logging level has strLevels sub-contexts,
|
// each logging level has strLevels sub-contexts,
|
||||||
// to exhaustively test all the combinations of setLevel(baseLevel) and isLevelEnabled(comparisonLevel) per config
|
// to exhaustively test all the combinations of
|
||||||
|
// setLevel(baseLevel) and isLevelEnabled(comparisonLevel) per config
|
||||||
strLevels.forEach(function (comparisonLevel) {
|
strLevels.forEach(function (comparisonLevel) {
|
||||||
var comparisonLevelSubContext = 'with isLevelEnabled('+comparisonLevel+')';
|
var comparisonLevelSubContext = 'with isLevelEnabled('+comparisonLevel+')';
|
||||||
|
|
||||||
// calculate this independently of log4js, but we'll add a vow later on to check that we're not mismatched with log4js
|
// calculate this independently of log4js, but we'll add a vow
|
||||||
|
// later on to check that we're not mismatched with log4js
|
||||||
var expectedResult = strLevels.indexOf(baseLevel) <= strLevels.indexOf(comparisonLevel);
|
var expectedResult = strLevels.indexOf(baseLevel) <= strLevels.indexOf(comparisonLevel);
|
||||||
|
|
||||||
// the topic simply gathers all the parameters for the vow into an object, to simplify the vow's work.
|
// the topic simply gathers all the parameters for the vow
|
||||||
batch[context][baseLevelSubContext][comparisonLevelSubContext] = {topic: function(baseLevel, log4js){
|
// into an object, to simplify the vow's work.
|
||||||
return {comparisonLevel: comparisonLevel, baseLevel: baseLevel, log4js: log4js, expectedResult: expectedResult};
|
subContext[comparisonLevelSubContext] = {
|
||||||
}};
|
topic: function(baseLevel, log4js) {
|
||||||
|
return {
|
||||||
|
comparisonLevel: comparisonLevel,
|
||||||
|
baseLevel: baseLevel,
|
||||||
|
log4js: log4js,
|
||||||
|
expectedResult: expectedResult
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
var vow = 'should return '+expectedResult;
|
var vow = 'should return '+expectedResult;
|
||||||
batch[context][baseLevelSubContext][comparisonLevelSubContext][vow] = function(topic){
|
subContext[comparisonLevelSubContext][vow] = function(topic) {
|
||||||
var result = topic.log4js.getLogger(getLoggerName(topic.baseLevel)).isLevelEnabled(topic.log4js.levels.toLevel(topic.comparisonLevel));
|
var result = topic.log4js
|
||||||
assert.equal(result, topic.expectedResult, 'Failed: '+getLoggerName(topic.baseLevel)+'.isLevelEnabled( '+topic.comparisonLevel+' ) returned '+result);
|
.getLogger(getLoggerName(topic.baseLevel))
|
||||||
|
.isLevelEnabled(topic.log4js.levels.toLevel(topic.comparisonLevel));
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
result,
|
||||||
|
topic.expectedResult,
|
||||||
|
'Failed: ' + getLoggerName(topic.baseLevel) +
|
||||||
|
'.isLevelEnabled( ' + topic.comparisonLevel + ' ) returned ' + result
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// the extra vow to check the comparison between baseLevel and comparisonLevel we performed earlier matches log4js' comparison too
|
// the extra vow to check the comparison between baseLevel and
|
||||||
batch[context][baseLevelSubContext][comparisonLevelSubContext]['finally checking for comparison mismatch with log4js'] = function(topic){
|
// comparisonLevel we performed earlier matches log4js'
|
||||||
var er = topic.log4js.levels.toLevel(topic.baseLevel).isLessThanOrEqualTo(topic.log4js.levels.toLevel(topic.comparisonLevel));
|
// comparison too
|
||||||
assert.equal(er, topic.expectedResult, 'Mismatch: for setLevel('+topic.baseLevel+') was expecting a comparison with '+topic.comparisonLevel+' to be '+topic.expectedResult);
|
var subSubContext = subContext[comparisonLevelSubContext];
|
||||||
|
subSubContext['finally checking for comparison mismatch with log4js'] = function(topic) {
|
||||||
|
var er = topic.log4js.levels.toLevel(topic.baseLevel)
|
||||||
|
.isLessThanOrEqualTo(topic.log4js.levels.toLevel(topic.comparisonLevel));
|
||||||
|
assert.equal(
|
||||||
|
er,
|
||||||
|
topic.expectedResult,
|
||||||
|
'Mismatch: for setLevel(' + topic.baseLevel +
|
||||||
|
') was expecting a comparison with ' + topic.comparisonLevel +
|
||||||
|
' to be ' + topic.expectedResult
|
||||||
|
);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
showProgress('Running tests');
|
showProgress('Running tests');
|
||||||
var v = vows.describe('log4js.configure(), with or without a "levels" property');
|
var v = vows.describe('log4js.configure(), with or without a "levels" property');
|
||||||
|
|
||||||
batches.forEach(function(batch) {v=v.addBatch(batch)});
|
batches.forEach(function(batch) {v=v.addBatch(batch);});
|
||||||
|
|
||||||
v.export(module);
|
v.export(module);
|
||||||
|
|
||||||
|
@ -26,7 +26,7 @@ vows.describe('log4js layouts').addBatch({
|
|||||||
toString: function() { return "ERROR"; }
|
toString: function() { return "ERROR"; }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
assert.equal(output, '\0x1B[31m[2010-12-05 14:18:30.045] [ERROR] cheese - \0x1B[39mnonsense');
|
assert.equal(output, '\x1B[31m[2010-12-05 14:18:30.045] [ERROR] cheese - \x1B[39mnonsense');
|
||||||
},
|
},
|
||||||
|
|
||||||
'should support the console.log format for the message': function(layout) {
|
'should support the console.log format for the message': function(layout) {
|
||||||
@ -38,7 +38,7 @@ vows.describe('log4js layouts').addBatch({
|
|||||||
toString: function() { return "ERROR"; }
|
toString: function() { return "ERROR"; }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
assert.equal(output, '\0x1B[31m[2010-12-05 14:18:30.045] [ERROR] cheese - \0x1B[39mthing 2');
|
assert.equal(output, '\x1B[31m[2010-12-05 14:18:30.045] [ERROR] cheese - \x1B[39mthing 2');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -258,7 +258,7 @@ vows.describe('log4js layouts').addBatch({
|
|||||||
test(args, '%-10p', 'DEBUG ');
|
test(args, '%-10p', 'DEBUG ');
|
||||||
},
|
},
|
||||||
'%[%r%] should output colored time': function(args) {
|
'%[%r%] should output colored time': function(args) {
|
||||||
test(args, '%[%r%]', '\0x1B[36m14:18:30\0x1B[39m');
|
test(args, '%[%r%]', '\x1B[36m14:18:30\x1B[39m');
|
||||||
},
|
},
|
||||||
'%x{testString} should output the string stored in tokens': function(args) {
|
'%x{testString} should output the string stored in tokens': function(args) {
|
||||||
test(args, '%x{testString}', 'testStringToken');
|
test(args, '%x{testString}', 'testStringToken');
|
||||||
|
Loading…
Reference in New Issue
Block a user