moved logLevelFilter tests to vows

This commit is contained in:
csausdev 2010-12-06 17:26:23 +08:00 committed by Gareth Jones
parent c74120e499
commit 540a683566
25 changed files with 0 additions and 4046 deletions

View File

@ -1,202 +0,0 @@
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.

View File

@ -1,67 +0,0 @@
# log4js-node
This is a conversion of the [log4js](http://log4js.berlios.de/index.html)
framework to work with [node](http://nodejs.org). I've mainly stripped out the browser-specific code
and tidied up some of the javascript. It includes a basic file logger, with log rolling based on file size.
NOTE: since v0.2.0 require('log4js') returns a function, so you need to call that function in your code before you can use it. I've done this to make testing easier (allows dependency injection).
## installation
npm install log4js
## tests
Tests now use [vows](http://vowsjs.org), run with `vows test/logging.js`. I am slowly porting the previous tests from jspec (run those with `node tests.js`), since jspec is no longer maintained.
## usage
Minimalist version:
var log4js = require('log4js')();
var logger = log4js.getLogger();
logger.debug("Some debug messages");
By default, log4js outputs to stdout with the coloured layout (thanks to [masylum](http://github.com/masylum)), so for the above you would see:
[2010-01-17 11:43:37.987] [DEBUG] [default] - Some debug messages
See example.js:
var log4js = require('log4js')(); //note the need to call the function
log4js.addAppender(log4js.consoleAppender());
log4js.addAppender(log4js.fileAppender('logs/cheese.log'), 'cheese');
var logger = log4js.getLogger('cheese');
logger.setLevel('ERROR');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');
Output
[2010-01-17 11:43:37.987] [ERROR] cheese - Cheese is too ripe!
[2010-01-17 11:43:37.990] [FATAL] cheese - Cheese was breeding ground for listeria.
## configuration
You can either configure the appenders and log levels manually (as above), or provide a
configuration file (`log4js.configure('path/to/file.json')`) explicitly, or just let log4js look for a file called `log4js.json` (it looks in the current directory first, then the require paths, and finally looks for the default config included in the same directory as the `log4js.js` file).
An example file can be found in `test/log4js.json`. An example config file with log rolling is in `test/with-log-rolling.json`
## todo
patternLayout has no tests. This is mainly because I haven't found a use for it yet,
and am not entirely sure what it was supposed to do. It is more-or-less intact from
the original log4js.
## author (of this node version)
Gareth Jones (csausdev - gareth.jones@sensis.com.au)
## License
The original log4js was distributed under the Apache 2.0 License, and so is this. I've tried to
keep the original copyright and author credits in place, except in sections that I have rewritten
extensively.

View File

@ -1,13 +0,0 @@
var log4js = require('./lib/log4js')();
log4js.addAppender(log4js.consoleAppender());
log4js.addAppender(log4js.fileAppender('cheese.log'), 'cheese');
var logger = log4js.getLogger('cheese');
logger.setLevel('ERROR');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');

View File

@ -1,699 +0,0 @@
/*
* 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.
*/
/*jsl:option explicit*/
/**
* @fileoverview log4js is a library to log in JavaScript in similar manner
* than in log4j for Java. The API should be nearly the same.
*
* This file contains all log4js code and is the only file required for logging.
*
* <h3>Example:</h3>
* <pre>
* var logging = require('log4js-node')();
* //add an appender that logs all messages to stdout.
* logging.addAppender(logging.consoleAppender());
* //add an appender that logs "some-category" to a file
* logging.addAppender(logging.fileAppender("file.log"), "some-category");
* //get a logger
* var log = logging.getLogger("some-category");
* log.setLevel(logging.levels.TRACE); //set the Level
*
* ...
*
* //call the log
* log.trace("trace me" );
* </pre>
*
* @version 1.0
* @author Stephan Strittmatter - http://jroller.com/page/stritti
* @author Seth Chisamore - http://www.chisamore.com
* @since 2005-05-20
* @static
* Website: http://log4js.berlios.de
*/
module.exports = function (fileSystem, standardOutput, configPaths) {
var fs = fileSystem || require('fs'),
standardOutput = standardOutput || console.log,
configPaths = configPaths || require.paths,
sys = require('sys'),
events = require('events'),
path = require('path'),
DEFAULT_CATEGORY = '[default]',
ALL_CATEGORIES = '[all]',
loggers = {},
appenders = {},
levels = {
ALL: new Level(Number.MIN_VALUE, "ALL", "grey"),
TRACE: new Level(5000, "TRACE", "blue"),
DEBUG: new Level(10000, "DEBUG", "cyan"),
INFO: new Level(20000, "INFO", "green"),
WARN: new Level(30000, "WARN", "yellow"),
ERROR: new Level(40000, "ERROR", "red"),
FATAL: new Level(50000, "FATAL", "magenta"),
OFF: new Level(Number.MAX_VALUE, "OFF", "grey")
},
appenderMakers = {
"file": function(config) {
var layout;
if (config.layout) {
layout = layoutMakers[config.layout.type](config.layout);
}
return fileAppender(config.filename, layout, config.maxLogSize, config.backups, config.pollInterval);
},
"console": function(config) {
var layout;
if (config.layout) {
layout = layoutMakers[config.layout.type](config.layout);
}
return consoleAppender(layout);
},
"logLevelFilter": function(config) {
var appender = appenderMakers[config.appender.type](config.appender);
return logLevelFilter(config.level, appender);
}
},
layoutMakers = {
"messagePassThrough": function() { return messagePassThroughLayout; },
"basic": function() { return basicLayout; },
"pattern": function (config) {
var pattern = config.pattern || undefined;
return patternLayout(pattern);
}
};
/**
* Get a logger instance. Instance is cached on categoryName level.
* @param {String} categoryName name of category to log to.
* @return {Logger} instance of logger for the category
* @static
*/
function getLogger (categoryName) {
// Use default logger if categoryName is not specified or invalid
if (!(typeof categoryName == "string")) {
categoryName = DEFAULT_CATEGORY;
}
var appenderList;
if (!loggers[categoryName]) {
// Create the logger for this name if it doesn't already exist
loggers[categoryName] = new Logger(categoryName);
if (appenders[categoryName]) {
appenderList = appenders[categoryName];
appenderList.forEach(function(appender) {
loggers[categoryName].addListener("log", appender);
});
}
if (appenders[ALL_CATEGORIES]) {
appenderList = appenders[ALL_CATEGORIES];
appenderList.forEach(function(appender) {
loggers[categoryName].addListener("log", appender);
});
}
}
return loggers[categoryName];
}
/**
* args are appender, then zero or more categories
*/
function addAppender () {
var args = Array.prototype.slice.call(arguments);
var appender = args.shift();
if (args.length == 0 || args[0] === undefined) {
args = [ ALL_CATEGORIES ];
}
//argument may already be an array
if (args[0].forEach) {
args = args[0];
}
args.forEach(function(category) {
if (!appenders[category]) {
appenders[category] = [];
}
appenders[category].push(appender);
if (category === ALL_CATEGORIES) {
for (var logger in loggers) {
if (loggers.hasOwnProperty(logger)) {
loggers[logger].addListener("log", appender);
}
}
} else if (loggers[category]) {
loggers[category].addListener("log", appender);
}
});
}
function clearAppenders () {
appenders = [];
for (var logger in loggers) {
if (loggers.hasOwnProperty(logger)) {
loggers[logger].removeAllListeners("log");
}
}
}
function configure (configurationFile) {
if (configurationFile) {
try {
var config = JSON.parse(fs.readFileSync(configurationFile, "utf8"));
configureAppenders(config.appenders);
configureLevels(config.levels);
} catch (e) {
throw new Error("Problem reading log4js config file " + configurationFile + ". Error was " + e.message);
}
}
}
function findConfiguration() {
//add current directory onto the list of configPaths
var paths = ['.'].concat(configPaths);
//add this module's directory to the end of the list, so that we pick up the default config
paths.push(__dirname);
var pathsWithConfig = paths.filter( function (pathToCheck) {
try {
fs.statSync(path.join(pathToCheck, "log4js.json"));
return true;
} catch (e) {
return false;
}
});
if (pathsWithConfig.length > 0) {
return path.join(pathsWithConfig[0], 'log4js.json');
}
return undefined;
}
function configureAppenders(appenderList) {
clearAppenders();
if (appenderList) {
appenderList.forEach(function(appenderConfig) {
var appender = appenderMakers[appenderConfig.type](appenderConfig);
if (appender) {
addAppender(appender, appenderConfig.category);
} else {
throw new Error("log4js configuration problem for "+sys.inspect(appenderConfig));
}
});
} else {
addAppender(consoleAppender);
}
}
function configureLevels(levels) {
if (levels) {
for (var category in levels) {
if (levels.hasOwnProperty(category)) {
getLogger(category).setLevel(levels[category]);
}
}
}
}
function Level(level, levelStr, colour) {
this.level = level;
this.levelStr = levelStr;
this.colour = colour;
}
/**
* converts given String to corresponding Level
* @param {String} sArg String value of Level
* @param {Log4js.Level} defaultLevel default Level, if no String representation
* @return Level object
* @type Log4js.Level
*/
Level.toLevel = function(sArg, defaultLevel) {
if (sArg === null) {
return defaultLevel;
}
if (typeof sArg == "string") {
var s = sArg.toUpperCase();
if (levels[s]) {
return levels[s];
}
}
return defaultLevel;
};
Level.prototype.toString = function() {
return this.levelStr;
};
Level.prototype.isLessThanOrEqualTo = function(otherLevel) {
return this.level <= otherLevel.level;
};
Level.prototype.isGreaterThanOrEqualTo = function(otherLevel) {
return this.level >= otherLevel.level;
};
/**
* Models a logging event.
* @constructor
* @param {String} categoryName name of category
* @param {Log4js.Level} level level of message
* @param {String} message message to log
* @param {Log4js.Logger} logger the associated logger
* @author Seth Chisamore
*/
function LoggingEvent (categoryName, level, message, exception, logger) {
this.startTime = new Date();
this.categoryName = categoryName;
this.message = message;
this.exception = exception;
this.level = level;
this.logger = logger;
}
/**
* Logger to log messages.
* use {@see Log4js#getLogger(String)} to get an instance.
* @constructor
* @param name name of category to log to
* @author Stephan Strittmatter
*/
function Logger (name, level) {
this.category = name || DEFAULT_CATEGORY;
this.level = Level.toLevel(level, levels.TRACE);
}
sys.inherits(Logger, events.EventEmitter);
Logger.prototype.setLevel = function(level) {
this.level = Level.toLevel(level, levels.TRACE);
};
Logger.prototype.log = function(logLevel, message, exception) {
var loggingEvent = new LoggingEvent(this.category, logLevel, message, exception, this);
this.emit("log", loggingEvent);
};
Logger.prototype.isLevelEnabled = function(otherLevel) {
return this.level.isLessThanOrEqualTo(otherLevel);
};
['Trace','Debug','Info','Warn','Error','Fatal'].forEach(
function(levelString) {
var level = Level.toLevel(levelString);
Logger.prototype['is'+levelString+'Enabled'] = function() {
return this.isLevelEnabled(level);
};
Logger.prototype[levelString.toLowerCase()] = function (message, exception) {
if (this.isLevelEnabled(level)) {
this.log(level, message, exception);
}
};
}
);
/**
* Get the default logger instance.
* @return {Logger} instance of default logger
* @static
*/
function getDefaultLogger () {
return getLogger(DEFAULT_CATEGORY);
}
function consoleAppender (layout) {
layout = layout || colouredLayout;
return function(loggingEvent) {
standardOutput(layout(loggingEvent));
};
}
/**
* 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 layout a function that takes a logevent and returns a string (defaults to basicLayout).
* @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)
* @param filePollInterval - the time in seconds between file size checks (default 30s)
*/
function fileAppender (file, layout, logSize, numBackups, filePollInterval) {
layout = layout || basicLayout;
//syncs are generally bad, but we need
//the file to be open before we start doing any writing.
var logFile = fs.openSync(file, 'a', 0644);
if (logSize > 0) {
setupLogRolling(logFile, file, logSize, numBackups || 5, (filePollInterval * 1000) || 30000);
}
return function(loggingEvent) {
fs.write(logFile, layout(loggingEvent)+'\n', null, "utf8");
};
}
function setupLogRolling (logFile, filename, logSize, numBackups, filePollInterval) {
fs.watchFile(filename,
{
persistent: false,
interval: filePollInterval
},
function (curr, prev) {
if (curr.size >= logSize) {
rollThatLog(logFile, filename, numBackups);
}
}
);
}
function rollThatLog (logFile, filename, numBackups) {
//doing all of this fs stuff sync, because I don't want to lose any log events.
//first close the current one.
fs.closeSync(logFile);
//roll the backups (rename file.n-1 to file.n, where n <= numBackups)
for (var i=numBackups; i > 0; i--) {
if (i > 1) {
if (fileExists(filename + '.' + (i-1))) {
fs.renameSync(filename+'.'+(i-1), filename+'.'+i);
}
} else {
fs.renameSync(filename, filename+'.1');
}
}
//open it up again
logFile = fs.openSync(filename, 'a', 0644);
}
function fileExists (filename) {
try {
fs.statSync(filename);
return true;
} catch (e) {
return false;
}
}
function logLevelFilter (levelString, appender) {
var level = Level.toLevel(levelString);
return function(logEvent) {
if (logEvent.level.isGreaterThanOrEqualTo(level)) {
appender(logEvent);
}
}
}
/**
* BasicLayout is a simple layout for storing the logs. The logs are stored
* in following format:
* <pre>
* [startTime] [logLevel] categoryName - message\n
* </pre>
*
* @author Stephan Strittmatter
*/
function basicLayout (loggingEvent) {
var timestampLevelAndCategory = '[' + loggingEvent.startTime.toFormattedString() + '] ';
timestampLevelAndCategory += '[' + loggingEvent.level.toString() + '] ';
timestampLevelAndCategory += loggingEvent.categoryName + ' - ';
var output = timestampLevelAndCategory + loggingEvent.message;
if (loggingEvent.exception) {
output += '\n'
output += timestampLevelAndCategory;
if (loggingEvent.exception.stack) {
output += loggingEvent.exception.stack;
} else {
output += loggingEvent.exception.name + ': '+loggingEvent.exception.message;
}
}
return output;
}
/**
* Taken from masylum's fork (https://github.com/masylum/log4js-node)
*/
function colorize (str, style) {
var styles = {
//styles
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
//grayscale
'white' : [37, 39],
'grey' : [90, 39],
'black' : [90, 39],
//colors
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
return '\033[' + styles[style][0] + 'm' + str +
'\033[' + styles[style][1] + 'm';
}
/**
* colouredLayout - taken from masylum's fork.
* same as basicLayout, but with colours.
*/
function colouredLayout (loggingEvent) {
var timestampLevelAndCategory = colorize('[' + loggingEvent.startTime.toFormattedString() + '] ', 'grey');
timestampLevelAndCategory += colorize(
'[' + loggingEvent.level.toString() + '] ', loggingEvent.level.colour
);
timestampLevelAndCategory += colorize(loggingEvent.categoryName + ' - ', 'grey');
var output = timestampLevelAndCategory + loggingEvent.message;
if (loggingEvent.exception) {
output += '\n'
output += timestampLevelAndCategory;
if (loggingEvent.exception.stack) {
output += loggingEvent.exception.stack;
} else {
output += loggingEvent.exception.name + ': '+loggingEvent.exception.message;
}
}
return output;
}
function messagePassThroughLayout (loggingEvent) {
return loggingEvent.message;
}
/**
* PatternLayout
* Takes a pattern string and returns a layout function.
* @author Stephan Strittmatter
*/
function patternLayout (pattern) {
var TTCC_CONVERSION_PATTERN = "%r %p %c - %m%n";
var regex = /%(-?[0-9]+)?(\.?[0-9]+)?([cdmnpr%])(\{([^\}]+)\})?|([^%]+)/;
pattern = pattern || patternLayout.TTCC_CONVERSION_PATTERN;
return function(loggingEvent) {
var formattedString = "";
var result;
var searchString = this.pattern;
while ((result = regex.exec(searchString))) {
var matchedString = result[0];
var padding = result[1];
var truncation = result[2];
var conversionCharacter = result[3];
var specifier = result[5];
var text = result[6];
// Check if the pattern matched was just normal text
if (text) {
formattedString += "" + text;
} else {
// Create a raw replacement string based on the conversion
// character and specifier
var replacement = "";
switch(conversionCharacter) {
case "c":
var loggerName = loggingEvent.categoryName;
if (specifier) {
var precision = parseInt(specifier, 10);
var loggerNameBits = loggingEvent.categoryName.split(".");
if (precision >= loggerNameBits.length) {
replacement = loggerName;
} else {
replacement = loggerNameBits.slice(loggerNameBits.length - precision).join(".");
}
} else {
replacement = loggerName;
}
break;
case "d":
var dateFormat = Date.ISO8601_FORMAT;
if (specifier) {
dateFormat = specifier;
// Pick up special cases
if (dateFormat == "ISO8601") {
dateFormat = Date.ISO8601_FORMAT;
} else if (dateFormat == "ABSOLUTE") {
dateFormat = Date.ABSOLUTETIME_FORMAT;
} else if (dateFormat == "DATE") {
dateFormat = Date.DATETIME_FORMAT;
}
}
// Format the date
replacement = loggingEvent.startTime.toFormattedString(dateFormat);
break;
case "m":
replacement = loggingEvent.message;
break;
case "n":
replacement = "\n";
break;
case "p":
replacement = loggingEvent.level.toString();
break;
case "r":
replacement = "" + loggingEvent.startTime.toLocaleTimeString();
break;
case "%":
replacement = "%";
break;
default:
replacement = matchedString;
break;
}
// Format the replacement according to any padding or
// truncation specified
var len;
// First, truncation
if (truncation) {
len = parseInt(truncation.substr(1), 10);
replacement = replacement.substring(0, len);
}
// Next, padding
if (padding) {
if (padding.charAt(0) == "-") {
len = parseInt(padding.substr(1), 10);
// Right pad with spaces
while (replacement.length < len) {
replacement += " ";
}
} else {
len = parseInt(padding, 10);
// Left pad with spaces
while (replacement.length < len) {
replacement = " " + replacement;
}
}
}
formattedString += replacement;
}
searchString = searchString.substr(result.index + result[0].length);
}
return formattedString;
};
};
//set ourselves up if we can find a default log4js.json
configure(findConfiguration());
return {
getLogger: getLogger,
getDefaultLogger: getDefaultLogger,
addAppender: addAppender,
clearAppenders: clearAppenders,
configure: configure,
levels: levels,
consoleAppender: consoleAppender,
fileAppender: fileAppender,
logLevelFilter: logLevelFilter,
basicLayout: basicLayout,
messagePassThroughLayout: messagePassThroughLayout,
patternLayout: patternLayout,
colouredLayout: colouredLayout,
coloredLayout: colouredLayout
};
}
Date.ISO8601_FORMAT = "yyyy-MM-dd hh:mm:ss.SSS";
Date.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ssO";
Date.DATETIME_FORMAT = "dd MMM YYYY hh:mm:ss.SSS";
Date.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS";
Date.prototype.toFormattedString = function(format) {
format = format || Date.ISO8601_FORMAT;
var vDay = addZero(this.getDate());
var vMonth = addZero(this.getMonth()+1);
var vYearLong = addZero(this.getFullYear());
var vYearShort = addZero(this.getFullYear().toString().substring(3,4));
var vYear = (format.indexOf("yyyy") > -1 ? vYearLong : vYearShort);
var vHour = addZero(this.getHours());
var vMinute = addZero(this.getMinutes());
var vSecond = addZero(this.getSeconds());
var vMillisecond = padWithZeros(this.getMilliseconds(), 3);
var vTimeZone = offset(this);
var formatted = format
.replace(/dd/g, vDay)
.replace(/MM/g, vMonth)
.replace(/y{1,4}/g, vYear)
.replace(/hh/g, vHour)
.replace(/mm/g, vMinute)
.replace(/ss/g, vSecond)
.replace(/SSS/g, vMillisecond)
.replace(/O/g, vTimeZone);
return formatted;
function padWithZeros(vNumber, width) {
var numAsString = vNumber + "";
while (numAsString.length < width) {
numAsString = "0" + numAsString;
}
return numAsString;
}
function addZero(vNumber) {
return padWithZeros(vNumber, 2);
}
/**
* Formats the TimeOffest
* Thanks to http://www.svendtofte.com/code/date_format/
* @private
*/
function offset(date) {
// Difference to Greenwich time (GMT) in hours
var os = Math.abs(date.getTimezoneOffset());
var h = String(Math.floor(os/60));
var m = String(os%60);
h.length == 1? h = "0"+h:1;
m.length == 1? m = "0"+m:1;
return date.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
}
};

View File

@ -1,7 +0,0 @@
{
"appenders": [
{
"type": "console"
}
]
}

View File

@ -1,23 +0,0 @@
{
"name": "log4js",
"version": "0.2.0",
"description": "Port of Log4js to work with node.",
"keywords": [
"logging",
"log",
"log4j",
"node"
],
"main": "./lib/log4js",
"author": "Gareth Jones <gareth.jones@sensis.com.au>",
"bugs": {
"web": "http://github.com/csausdev/log4js-node/issues"
},
"engines": [ "node >=0.1.100" ],
"scripts": {
"test": "test.js"
},
"directories": {
"test": "spec"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 321 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 B

View File

@ -1,149 +0,0 @@
body.jspec {
margin: 45px 0;
font: 12px "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;
background: #efefef url(images/bg.png) top left repeat-x;
text-align: center;
}
#jspec {
margin: 0 auto;
padding-top: 30px;
width: 1008px;
background: url(images/vr.png) top left repeat-y;
text-align: left;
}
#jspec-top {
position: relative;
margin: 0 auto;
width: 1008px;
height: 40px;
background: url(images/sprites.bg.png) top left no-repeat;
}
#jspec-bottom {
margin: 0 auto;
width: 1008px;
height: 15px;
background: url(images/sprites.bg.png) bottom left no-repeat;
}
#jspec .loading {
margin-top: -45px;
width: 1008px;
height: 80px;
background: url(images/loading.gif) 50% 50% no-repeat;
}
#jspec-title {
position: absolute;
top: 15px;
left: 20px;
width: 160px;
font-size: 22px;
font-weight: normal;
background: url(images/sprites.png) 0 -126px no-repeat;
text-align: center;
}
#jspec-title em {
font-size: 10px;
font-style: normal;
color: #BCC8D1;
}
#jspec-report * {
margin: 0;
padding: 0;
background: none;
border: none;
}
#jspec-report {
padding: 15px 40px;
font: 11px "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;
color: #7B8D9B;
}
#jspec-report.has-failures {
padding-bottom: 30px;
}
#jspec-report .hidden {
display: none;
}
#jspec-report .heading {
margin-bottom: 15px;
}
#jspec-report .heading span {
padding-right: 10px;
}
#jspec-report .heading .passes em {
color: #0ea0eb;
}
#jspec-report .heading .failures em {
color: #FA1616;
}
#jspec-report table {
font-size: 11px;
border-collapse: collapse;
}
#jspec-report td {
padding: 8px;
text-indent: 30px;
color: #7B8D9B;
}
#jspec-report tr.body {
display: none;
}
#jspec-report tr.body pre {
margin: 0;
padding: 0 0 5px 25px;
}
#jspec-report tr.even:hover + tr.body,
#jspec-report tr.odd:hover + tr.body {
display: block;
}
#jspec-report tr td:first-child em {
display: block;
clear: both;
font-style: normal;
font-weight: normal;
color: #7B8D9B;
}
#jspec-report tr.even:hover,
#jspec-report tr.odd:hover {
text-shadow: 1px 1px 1px #fff;
background: #F2F5F7;
}
#jspec-report td + td {
padding-right: 0;
width: 15px;
}
#jspec-report td.pass {
background: url(images/sprites.png) 3px -7px no-repeat;
}
#jspec-report td.fail {
background: url(images/sprites.png) 3px -158px no-repeat;
font-weight: bold;
color: #FC0D0D;
}
#jspec-report td.requires-implementation {
background: url(images/sprites.png) 3px -333px no-repeat;
}
#jspec-report tr.description td {
margin-top: 25px;
padding-top: 25px;
font-size: 12px;
font-weight: bold;
text-indent: 0;
color: #1a1a1a;
}
#jspec-report tr.description:first-child td {
border-top: none;
}
#jspec-report .assertion {
display: block;
float: left;
margin: 0 0 0 1px;
padding: 0;
width: 1px;
height: 5px;
background: #7B8D9B;
}
#jspec-report .assertion.failed {
background: red;
}
.jspec-sandbox {
display: none;
}

View File

@ -1,115 +0,0 @@
// JSpec - Growl - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
;(function(){
Growl = {
// --- Version
version: '1.0.0',
/**
* Execute the given _cmd_, returning an array of lines from stdout.
*
* Examples:
*
* Growl.exec('growlnotify', '-m', msg)
*
* @param {string ...} cmd
* @return {array}
* @api public
*/
exec: function(cmd) {
var lines = [], line
with (JavaImporter(java.lang, java.io)) {
var proccess = Runtime.getRuntime().exec(Array.prototype.slice.call(arguments))
var stream = new DataInputStream(proccess.getInputStream())
while (line = stream.readLine())
lines.push(line + '')
stream.close()
}
return lines
},
/**
* Return the extension of the given _path_ or null.
*
* @param {string} path
* @return {string}
* @api private
*/
extname: function(path) {
return path.lastIndexOf('.') != -1 ?
path.slice(path.lastIndexOf('.') + 1, path.length) :
null
},
/**
* Version of the 'growlnotify' binary.
*
* @return {string}
* @api private
*/
binVersion: function() {
try { return this.exec('growlnotify', '-v')[0].split(' ')[1] } catch (e) {}
},
/**
* Send growl notification _msg_ with _options_.
*
* Options:
*
* - title Notification title
* - sticky Make the notification stick (defaults to false)
* - name Application name (defaults to growlnotify)
* - image
* - path to an icon sets --iconpath
* - path to an image sets --image
* - capitalized word sets --appIcon
* - filename uses extname as --icon
* - otherwise treated as --icon
*
* Examples:
*
* Growl.notify('New email')
* Growl.notify('5 new emails', { title: 'Thunderbird' })
*
* @param {string} msg
* @param {options} hash
* @api public
*/
notify: function(msg, options) {
options = options || {}
var args = ['growlnotify', '-m', msg]
if (!this.binVersion()) throw new Error('growlnotify executable is required')
if (image = options.image) {
var flag, ext = this.extname(image)
flag = flag || ext == 'icns' && 'iconpath'
flag = flag || /^[A-Z]/.test(image) && 'appIcon'
flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'
flag = flag || ext && (image = ext) && 'icon'
flag = flag || 'icon'
args.push('--' + flag, image)
}
if (options.sticky) args.push('--sticky')
if (options.name) args.push('--name', options.name)
if (options.title) args.push(options.title)
this.exec.apply(this, args)
}
}
JSpec.include({
name: 'Growl',
reporting: function(options){
var stats = JSpec.stats
if (stats.failures) Growl.notify('failed ' + stats.failures + ' assertions', { title: 'JSpec'})
else Growl.notify('passed ' + stats.passes + ' assertions', { title: 'JSpec' })
}
})
})()

View File

@ -1,71 +0,0 @@
// JSpec - jQuery - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
JSpec
.requires('jQuery', 'when using jspec.jquery.js')
.include({
name: 'jQuery',
// --- Initialize
init : function() {
jQuery.ajaxSetup({ async: false })
},
// --- Utilities
utilities : {
element: jQuery,
elements: jQuery,
sandbox : function() {
return jQuery('<div class="sandbox"></div>')
}
},
// --- Matchers
matchers : {
have_tag : "jQuery(expected, actual).length == 1",
have_one : "alias have_tag",
have_tags : "jQuery(expected, actual).length > 1",
have_many : "alias have_tags",
have_child : "jQuery(actual).children(expected).length == 1",
have_children : "jQuery(actual).children(expected).length > 1",
have_text : "jQuery(actual).text() == expected",
have_value : "jQuery(actual).val() == expected",
be_enabled : "!jQuery(actual).attr('disabled')",
have_class : "jQuery(actual).hasClass(expected)",
be_visible : function(actual) {
return jQuery(actual).css('display') != 'none' &&
jQuery(actual).css('visibility') != 'hidden' &&
jQuery(actual).attr('type') != 'hidden'
},
be_hidden : function(actual) {
return !JSpec.does(actual, 'be_visible')
},
have_classes : function(actual) {
return !JSpec.any(JSpec.toArray(arguments, 1), function(arg){
return !JSpec.does(actual, 'have_class', arg)
})
},
have_attr : function(actual, attr, value) {
return value ? jQuery(actual).attr(attr) == value:
jQuery(actual).attr(attr)
},
'be disabled selected checked' : function(attr) {
return 'jQuery(actual).attr("' + attr + '")'
},
'have type id title alt href src sel rev name target' : function(attr) {
return function(actual, value) {
return JSpec.does(actual, 'have_attr', attr, value)
}
}
}
})

File diff suppressed because it is too large Load Diff

View File

@ -1,39 +0,0 @@
// JSpec - Shell - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
;(function(){
var _quit = quit
Shell = {
// --- Global
main: this,
// --- Commands
commands: {
quit: ['Terminate the shell', function(){ _quit() }],
exit: ['Terminate the shell', function(){ _quit() }],
p: ['Inspect an object', function(o){ return o.toSource() }]
},
/**
* Start the interactive shell.
*
* @api public
*/
start : function() {
for (var name in this.commands)
if (this.commands.hasOwnProperty(name))
this.commands[name][1].length ?
this.main[name] = this.commands[name][1] :
this.main.__defineGetter__(name, this.commands[name][1])
}
}
Shell.start()
})()

View File

@ -1,90 +0,0 @@
// JSpec - Mock Timers - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
;(function(){
/**
* Version.
*/
mockTimersVersion = '1.0.2'
/**
* Localized timer stack.
*/
var timers = []
/**
* Set mock timeout with _callback_ and timeout of _ms_.
*
* @param {function} callback
* @param {int} ms
* @return {int}
* @api public
*/
setTimeout = function(callback, ms) {
var id
return id = setInterval(function(){
callback()
clearInterval(id)
}, ms)
}
/**
* Set mock interval with _callback_ and interval of _ms_.
*
* @param {function} callback
* @param {int} ms
* @return {int}
* @api public
*/
setInterval = function(callback, ms) {
callback.step = ms, callback.current = callback.last = 0
return timers[timers.length] = callback, timers.length
}
/**
* Destroy timer with _id_.
*
* @param {int} id
* @return {bool}
* @api public
*/
clearInterval = clearTimeout = function(id) {
return delete timers[--id]
}
/**
* Reset timers.
*
* @return {array}
* @api public
*/
resetTimers = function() {
return timers = []
}
/**
* Increment each timers internal clock by _ms_.
*
* @param {int} ms
* @api public
*/
tick = function(ms) {
for (var i = 0, len = timers.length; i < len; ++i)
if (timers[i] && (timers[i].current += ms))
if (timers[i].current - timers[i].last >= timers[i].step) {
var times = Math.floor((timers[i].current - timers[i].last) / timers[i].step)
var remainder = (timers[i].current - timers[i].last) % timers[i].step
timers[i].last = timers[i].current - remainder
while (times-- && timers[i]) timers[i]()
}
}
})()

View File

@ -1,193 +0,0 @@
// JSpec - XHR - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
(function(){
// --- Original XMLHttpRequest
var OriginalXMLHttpRequest = 'XMLHttpRequest' in this ?
XMLHttpRequest :
function(){}
var OriginalActiveXObject = 'ActiveXObject' in this ?
ActiveXObject :
undefined
// --- MockXMLHttpRequest
var MockXMLHttpRequest = function() {
this.requestHeaders = {}
}
MockXMLHttpRequest.prototype = {
status: 0,
async: true,
readyState: 0,
responseText: '',
abort: function(){},
onreadystatechange: function(){},
/**
* Return response headers hash.
*/
getAllResponseHeaders : function(){
return this.responseHeaders
},
/**
* Return case-insensitive value for header _name_.
*/
getResponseHeader : function(name) {
return this.responseHeaders[name.toLowerCase()]
},
/**
* Set case-insensitive _value_ for header _name_.
*/
setRequestHeader : function(name, value) {
this.requestHeaders[name.toLowerCase()] = value
},
/**
* Open mock request.
*/
open : function(method, url, async, user, password) {
this.user = user
this.password = password
this.url = url
this.readyState = 1
this.method = method.toUpperCase()
if (async != undefined) this.async = async
if (this.async) this.onreadystatechange()
},
/**
* Send request _data_.
*/
send : function(data) {
var self = this
this.data = data
this.readyState = 4
if (this.method == 'HEAD') this.responseText = null
this.responseHeaders['content-length'] = (this.responseText || '').length
if(this.async) this.onreadystatechange()
lastRequest = function(){
return self
}
}
}
// --- Response status codes
JSpec.statusCodes = {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
300: 'Multiple Choice',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported'
}
/**
* Mock XMLHttpRequest requests.
*
* mockRequest().and_return('some data', 'text/plain', 200, { 'X-SomeHeader' : 'somevalue' })
*
* @return {hash}
* @api public
*/
function mockRequest() {
return { and_return : function(body, type, status, headers) {
XMLHttpRequest = MockXMLHttpRequest
ActiveXObject = false
status = status || 200
headers = headers || {}
headers['content-type'] = type
JSpec.extend(XMLHttpRequest.prototype, {
responseText: body,
responseHeaders: headers,
status: status,
statusText: JSpec.statusCodes[status]
})
}}
}
/**
* Unmock XMLHttpRequest requests.
*
* @api public
*/
function unmockRequest() {
XMLHttpRequest = OriginalXMLHttpRequest
ActiveXObject = OriginalActiveXObject
}
JSpec.include({
name: 'Mock XHR',
// --- Utilities
utilities : {
mockRequest: mockRequest,
unmockRequest: unmockRequest
},
// --- Hooks
afterSpec : function() {
unmockRequest()
},
// --- DSLs
DSLs : {
snake : {
mock_request: mockRequest,
unmock_request: unmockRequest,
last_request: function(){ return lastRequest() }
}
}
})
})()

View File

@ -1,164 +0,0 @@
describe 'log4js'
before
extend(context, {
log4js : require("log4js")()
});
end
before_each
log4js.clearAppenders();
event = '';
logger = log4js.getLogger('tests');
logger.setLevel("TRACE");
logger.addListener("log", function (logEvent) { event = logEvent; });
end
describe 'addAppender'
before_each
appenderEvent = undefined;
appender = function(logEvent) { appenderEvent = logEvent; };
end
describe 'without a category'
it 'should register the function as a listener for all loggers'
log4js.addAppender(appender);
logger.debug("This is a test");
appenderEvent.should.be event
end
it 'should also register as an appender for loggers if an appender for that category is defined'
var otherEvent;
log4js.addAppender(appender);
log4js.addAppender(function (evt) { otherEvent = evt; }, 'cheese');
var cheeseLogger = log4js.getLogger('cheese');
cheeseLogger.addListener("log", function (logEvent) { event = logEvent; });
cheeseLogger.debug('This is a test');
appenderEvent.should.be event
otherEvent.should.be event
otherEvent = undefined;
appenderEvent = undefined;
log4js.getLogger('pants').debug("this should not be propagated to otherEvent");
otherEvent.should.be undefined
appenderEvent.should.not.be undefined
appenderEvent.message.should.be "this should not be propagated to otherEvent"
cheeseLogger = null;
end
end
describe 'with a category'
it 'should only register the function as a listener for that category'
log4js.addAppender(appender, 'tests');
logger.debug('this is a test');
appenderEvent.should.be event
appenderEvent = undefined;
log4js.getLogger('some other category').debug('Cheese');
appenderEvent.should.be undefined
end
end
describe 'with multiple categories'
it 'should register the function as a listener for all the categories'
log4js.addAppender(appender, 'tests', 'biscuits');
logger.debug('this is a test');
appenderEvent.should.be event
appenderEvent = undefined;
var otherLogger = log4js.getLogger('biscuits');
otherLogger.debug("mmm... garibaldis");
appenderEvent.should.not.be undefined
appenderEvent.message.should.be "mmm... garibaldis"
appenderEvent = undefined;
otherLogger = null;
log4js.getLogger("something else").debug("pants");
appenderEvent.should.be undefined
end
it 'should register the function when the list of categories is an array'
log4js.addAppender(appender, ['tests', 'pants']);
logger.debug('this is a test');
appenderEvent.should.be event
appenderEvent = undefined;
var otherLogger = log4js.getLogger('pants');
otherLogger.debug("big pants");
appenderEvent.should.not.be undefined
appenderEvent.message.should.be "big pants"
appenderEvent = undefined;
otherLogger = null;
log4js.getLogger("something else").debug("pants");
appenderEvent.should.be undefined
end
end
end
describe 'basicLayout'
it 'should take a logevent and output a formatted string'
logger.debug('this is a test');
var output = log4js.basicLayout(event);
output.should.match /\[.*?\] \[DEBUG\] tests - this is a test/
end
it 'should output a stacktrace, message if the event has an error attached'
var error = new Error("Some made-up error");
var stack = error.stack.split(/\n/);
logger.debug('this is a test', error);
var output = log4js.basicLayout(event);
var lines = output.split(/\n/);
lines.length.should.be stack.length+1
lines[0].should.match /\[.*?\] \[DEBUG\] tests - this is a test/
lines[1].should.match /\[.*?\] \[DEBUG\] tests - Error: Some made-up error/
for (var i = 1; i < stack.length; i++) {
lines[i+1].should.eql stack[i]
}
end
it 'should output a name and message if the event has something that pretends to be an error'
logger.debug('this is a test', { name: 'Cheese', message: 'Gorgonzola smells.' });
var output = log4js.basicLayout(event);
var lines = output.split(/\n/);
lines.length.should.be 2
lines[0].should.match /\[.*?\] \[DEBUG\] tests - this is a test/
lines[1].should.match /\[.*?\] \[DEBUG\] tests - Cheese: Gorgonzola smells./
end
end
describe 'logLevelFilter'
it 'should only pass log events greater than or equal to its own level'
var logEvent;
log4js.addAppender(log4js.logLevelFilter('ERROR', function(evt) { logEvent = evt; }));
logger.debug('this should not trigger an event');
logEvent.should.be undefined
logger.warn('neither should this');
logEvent.should.be undefined
logger.error('this should, though');
logEvent.should.not.be undefined
logEvent.message.should.be 'this should, though'
logger.fatal('so should this')
logEvent.message.should.be 'so should this'
end
end
end

View File

@ -1,16 +0,0 @@
{
"appenders": [
{
"category": "tests",
"type": "file",
"filename": "tmp-tests.log",
"layout": {
"type": "messagePassThrough"
}
}
],
"levels": {
"tests": "WARN"
}
}

View File

@ -1,343 +0,0 @@
var vows = require('vows'),
assert = require('assert');
vows.describe('log4js').addBatch({
'getLogger': {
topic: function() {
var log4js = require('../lib/log4js')();
log4js.clearAppenders();
var logger = log4js.getLogger('tests');
logger.setLevel("DEBUG");
return logger;
},
'should take a category and return a logger': function(logger) {
assert.equal(logger.category, 'tests');
assert.equal(logger.level.toString(), "DEBUG");
assert.isFunction(logger.debug);
assert.isFunction(logger.info);
assert.isFunction(logger.warn);
assert.isFunction(logger.error);
assert.isFunction(logger.fatal);
},
'log events' : {
topic: function(logger) {
var events = [];
logger.addListener("log", function (logEvent) { events.push(logEvent); });
logger.debug("Debug event");
logger.trace("Trace event 1");
logger.trace("Trace event 2");
logger.warn("Warning event");
return events;
},
'should emit log events': function(events) {
assert.equal(events[0].level.toString(), 'DEBUG');
assert.equal(events[0].message, 'Debug event');
assert.instanceOf(events[0].startTime, Date);
},
'should not emit events of a lower level': function(events) {
assert.length(events, 2);
assert.equal(events[1].level.toString(), 'WARN');
}
},
},
'fileAppender': {
topic: function() {
var appender, logmessages = [], thing = "thing", fakeFS = {
openSync: function() {
assert.equal(arguments[0], './tmp-tests.log');
assert.equal(arguments[1], 'a');
assert.equal(arguments[2], 0644);
return thing;
},
write: function() {
assert.equal(arguments[0], thing);
assert.isString(arguments[1]);
assert.isNull(arguments[2]);
assert.equal(arguments[3], "utf8");
logmessages.push(arguments[1]);
},
watchFile: function() {
throw new Error("watchFile should not be called if logSize is not defined");
}
},
log4js = require('../lib/log4js')(fakeFS);
log4js.clearAppenders();
appender = log4js.fileAppender('./tmp-tests.log', log4js.messagePassThroughLayout);
log4js.addAppender(appender, 'file-test');
var logger = log4js.getLogger('file-test');
logger.debug("this is a test");
return logmessages;
},
'should write log messages to file': function(logmessages) {
assert.length(logmessages, 1);
assert.equal(logmessages, "this is a test\n");
}
},
'fileAppender - with rolling based on size and number of files to keep': {
topic: function() {
var watchCb,
filesOpened = [],
filesClosed = [],
filesRenamed = [],
newFilenames = [],
existingFiles = ['tests.log'],
log4js = require('../lib/log4js')({
watchFile: function(file, options, callback) {
assert.equal(file, 'tests.log');
assert.equal(options.persistent, false);
assert.equal(options.interval, 30000);
assert.isFunction(callback);
watchCb = callback;
},
openSync: function(file) {
assert.equal(file, 'tests.log');
filesOpened.push(file);
return file;
},
statSync: function(file) {
if (existingFiles.indexOf(file) < 0) {
throw new Error("this file doesn't exist");
} else {
return true;
}
},
renameSync: function(oldFile, newFile) {
filesRenamed.push(oldFile);
existingFiles.push(newFile);
},
closeSync: function(file) {
//it should always be closing tests.log
assert.equal(file, 'tests.log');
filesClosed.push(file);
}
});
var appender = log4js.fileAppender('tests.log', log4js.messagePassThroughLayout, 1024, 2, 30);
return [watchCb, filesOpened, filesClosed, filesRenamed, existingFiles];
},
'should close current log file, rename all old ones, open new one on rollover': function(args) {
var watchCb = args[0], filesOpened = args[1], filesClosed = args[2], filesRenamed = args[3], existingFiles = args[4];
assert.isFunction(watchCb);
//tell the watchCb that the file is below the threshold
watchCb({ size: 891 }, { size: 0 });
//filesOpened should still be the first one.
assert.length(filesOpened, 1);
//tell the watchCb that the file is now over the threshold
watchCb({ size: 1053 }, { size: 891 });
//it should have closed the first log file.
assert.length(filesClosed, 1);
//it should have renamed the previous log file
assert.length(filesRenamed, 1);
//and we should have two files now
assert.length(existingFiles, 2);
assert.deepEqual(existingFiles, ['tests.log', 'tests.log.1']);
//and opened a new log file.
assert.length(filesOpened, 2);
//now tell the watchCb that we've flipped over the threshold again
watchCb({ size: 1025 }, { size: 123 });
//it should have closed the old file
assert.length(filesClosed, 2);
//it should have renamed both the old log file, and the previous '.1' file
assert.length(filesRenamed, 3);
assert.deepEqual(filesRenamed, ['tests.log', 'tests.log.1', 'tests.log' ]);
//it should have renamed 2 more file
assert.length(existingFiles, 4);
assert.deepEqual(existingFiles, ['tests.log', 'tests.log.1', 'tests.log.2', 'tests.log.1']);
//and opened a new log file
assert.length(filesOpened, 3);
//tell the watchCb we've flipped again.
watchCb({ size: 1024 }, { size: 234 });
//close the old one again.
assert.length(filesClosed, 3);
//it should have renamed the old log file and the 2 backups, with the last one being overwritten.
assert.length(filesRenamed, 5);
assert.deepEqual(filesRenamed, ['tests.log', 'tests.log.1', 'tests.log', 'tests.log.1', 'tests.log' ]);
//it should have renamed 2 more files
assert.length(existingFiles, 6);
assert.deepEqual(existingFiles, ['tests.log', 'tests.log.1', 'tests.log.2', 'tests.log.1', 'tests.log.2', 'tests.log.1']);
//and opened a new log file
assert.length(filesOpened, 4);
}
},
'configure' : {
topic: function() {
var messages = {}, fakeFS = {
openSync: function(file) {
return file;
},
write: function(file, message) {
if (!messages.hasOwnProperty(file)) {
messages[file] = [];
}
messages[file].push(message);
},
readFileSync: function(file, encoding) {
return require('fs').readFileSync(file, encoding);
},
watchFile: function(file) {
messages.watchedFile = file;
}
},
log4js = require('../lib/log4js')(fakeFS);
return [ log4js, messages ];
},
'should load appender configuration from a json file': function(args) {
var log4js = args[0], messages = args[1];
delete messages['tmp-tests.log'];
log4js.clearAppenders();
//this config file defines one file appender (to ./tmp-tests.log)
//and sets the log level for "tests" to WARN
log4js.configure('test/log4js.json');
var logger = log4js.getLogger("tests");
logger.info('this should not be written to the file');
logger.warn('this should be written to the file');
assert.length(messages['tmp-tests.log'], 1);
assert.equal(messages['tmp-tests.log'][0], 'this should be written to the file\n');
},
'should handle logLevelFilter configuration': function(args) {
var log4js = args[0], messages = args[1];
delete messages['tmp-tests.log'];
delete messages['tmp-tests-warnings.log'];
log4js.clearAppenders();
log4js.configure('test/with-logLevelFilter.json');
var logger = log4js.getLogger("tests");
logger.info('main');
logger.error('both');
logger.warn('both');
logger.debug('main');
assert.length(messages['tmp-tests.log'], 4);
assert.length(messages['tmp-tests-warnings.log'], 2);
assert.deepEqual(messages['tmp-tests.log'], ['main\n','both\n','both\n','main\n']);
assert.deepEqual(messages['tmp-tests-warnings.log'], ['both\n','both\n']);
},
'should handle fileAppender with log rolling' : function(args) {
var log4js = args[0], messages = args[1];
delete messages['tmp-test.log'];
log4js.configure('test/with-log-rolling.json');
assert.equal(messages.watchedFile, 'tmp-test.log');
}
},
'with no appenders defined' : {
topic: function() {
var logger, message, log4js = require('../lib/log4js')(null, function (msg) { message = msg; } );
logger = log4js.getLogger("some-logger");
logger.debug("This is a test");
return message;
},
'should default to the console appender': function(message) {
assert.isTrue(/This is a test$/.test(message));
}
},
'default setup': {
topic: function() {
var pathsChecked = [],
message,
logger,
fakeFS = {
readFileSync: function (file, encoding) {
assert.equal(file, '/path/to/config/log4js.json');
assert.equal(encoding, 'utf8');
return '{ "appenders" : [ { "type": "console", "layout": { "type": "messagePassThrough" }} ] }';
},
statSync: function (path) {
pathsChecked.push(path);
if (path === '/path/to/config/log4js.json') {
return true;
} else {
throw new Error("no such file");
}
}
},
fakeConsoleLog = function (msg) { message = msg; },
fakeRequirePath = [ '/a/b/c', '/some/other/path', '/path/to/config', '/some/later/directory' ],
log4js = require('../lib/log4js')(fakeFS, fakeConsoleLog, fakeRequirePath),
logger = log4js.getLogger('a-test');
logger.debug("this is a test");
return [ pathsChecked, message ];
},
'should check current directory, require paths, and finally the module dir for log4js.json': function(args) {
var pathsChecked = args[0];
assert.deepEqual(pathsChecked, [
'log4js.json',
'/a/b/c/log4js.json',
'/some/other/path/log4js.json',
'/path/to/config/log4js.json',
'/some/later/directory/log4js.json',
require('path').normalize(__dirname + '/../lib/log4js.json')
]);
},
'should configure log4js from first log4js.json found': function(args) {
var message = args[1];
assert.equal(message, 'this is a test');
}
},
'colouredLayout': {
topic: function() {
return require('../lib/log4js')().colouredLayout;
},
'should apply level colour codes to output': function(layout) {
var output = layout({
message: "nonsense",
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
level: {
colour: "green",
toString: function() { return "ERROR"; }
}
});
assert.equal(output, '\033[90m[2010-12-05 14:18:30.045] \033[39m\033[32m[ERROR] \033[39m\033[90mcheese - \033[39mnonsense');
}
},
'messagePassThroughLayout': {
topic: function() {
return require('../lib/log4js')().messagePassThroughLayout;
},
'should take a logevent and output only the message' : function(layout) {
assert.equal(layout({
message: "nonsense",
startTime: new Date(2010, 11, 5, 14, 18, 30, 45),
categoryName: "cheese",
level: {
colour: "green",
toString: function() { return "ERROR"; }
}
}), "nonsense");
}
},
'Date extensions': {
topic: function() {
require('../lib/log4js');
return new Date(2010, 0, 11, 14, 31, 30, 5);
},
'should add a toFormattedString method to Date': function(date) {
assert.isFunction(date.toFormattedString);
},
'should default to a format': function(date) {
assert.equal(date.toFormattedString(), '2010-01-11 14:31:30.005');
}
}
}).export(module);

View File

@ -1,11 +0,0 @@
{
"appenders": [
{
"type": "file",
"filename": "tmp-test.log",
"maxLogSize": 1024,
"backups": 3,
"pollInterval": 15
}
]
}

View File

@ -1,28 +0,0 @@
{
"appenders": [
{
"category": "tests",
"type": "logLevelFilter",
"level": "WARN",
"appender": {
"type": "file",
"filename": "tmp-tests-warnings.log",
"layout": {
"type": "messagePassThrough"
}
}
},
{
"category": "tests",
"type": "file",
"filename": "tmp-tests.log",
"layout": {
"type": "messagePassThrough"
}
}
],
"levels": {
"tests": "DEBUG"
}
}

View File

@ -1,43 +0,0 @@
require.paths.unshift("./spec/lib", "./lib");
require("jspec");
var sys = require("sys"), fs = require("fs");
quit = process.exit
print = sys.puts
readFile = function(path) {
var result;
try {
result = fs.readFileSync(path, "utf8");
} catch (e) {
throw e;
}
return result;
}
var specsFound = false;
if (process.ARGV[2]) {
specsFound = true;
JSpec.exec('spec/spec.' + process.ARGV[2] + '.js');
} else {
var files = fs.readdirSync('spec/');
files.filter(
function (file) {
return file.indexOf('spec.') === 0;
}
).forEach(
function(file) {
specsFound = true;
JSpec.exec('spec/'+file);
}
);
}
if (specsFound) {
JSpec.run({ reporter: JSpec.reporters.Terminal, failuresOnly: false });
JSpec.report();
} else {
print("No tests to run. This makes me sad.");
}