Adding tests and cleaning up directories

This commit is contained in:
Mathew Kurian 2014-08-01 02:28:44 -05:00
parent 3720182b4a
commit 1ed172708b
13 changed files with 796 additions and 1008 deletions

22
.gitattributes vendored
View file

@ -1,22 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

216
.gitignore vendored
View file

@ -1,215 +1,3 @@
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
build/
[Bb]in/
[Oo]bj/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
*.pubxml
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
#############
## Windows detritus
#############
# Windows image file caches
node_modules
test/logs
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac crap
.DS_Store
#############
## Python
#############
*.py[co]
# Packages
*.egg
*.egg-info
dist/
build/
eggs/
parts/
var/
sdist/
develop-eggs/
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg

14
.jshintrc Normal file
View file

@ -0,0 +1,14 @@
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"unused": true,
"boss": true,
"eqnull": true,
"node": true
}

50
Gruntfile.js Normal file
View file

@ -0,0 +1,50 @@
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
'files': ['test/**/*.js'],
'usage': ['test/**/usage.js'],
'express-usage': ['test/**/express-usage.js']
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
},
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'nodeunit']
},
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};

202
LICENSE
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 2013 Mathew Kurian
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.

22
LICENSE-MIT Normal file
View file

@ -0,0 +1,22 @@
Copyright (c) 2014 Mathew Kurian
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

161
README.md
View file

@ -1,153 +1,26 @@
![Logo](__misc/scribejs design logo [a].png)
=======
**Lightweight NodeJS Logging**
Overview
=======
# Scribe.js
Unlike many of the libraries out there, Scribe.js allows logging on multiple files and is divided into folders by date. And it is possibly the easiest logging you can implement. And it does everything you need a basic logger to do.
- Save messages into log files organized by user, date, and type
- Print messages into console using colors indicating level of importance
Output Methods (Web | Console | File)
=======
Method#Web - Select Date
---
![Control Panel View 1](http://i.imgur.com/sXyDc09.png)
Method#Web - Select Log Type
---
![Control Panel View 1](http://i.imgur.com/NgCa8tR.png)
Method#Web - View Logs
---
![Control Panel View 1](http://i.imgur.com/ULkKn1X.png)
Method#Console - Command Prompt
---
![Command Prompt output](https://raw.github.com/bluejamesbond/Scribe.js/master/__misc/scribejs%20sample%20cmd%20%5Ba%5D.PNG)
Method#File - File
---
![Files output](https://raw.github.com/bluejamesbond/Scribe.js/master/__misc/scribejs%20sample%20file%20%5Ba%5D.PNG)
Method#File - Directory Layout
---
![Files Directory](https://raw.github.com/bluejamesbond/Scribe.js/master/__misc/scribejs%20sample%20directory%20%5Ba%5D.PNG)
## Getting Started
Install the module with: `npm install scribe-js`
How to use Scribe.js
=======
Using Sribe is as simple as putting the contents of the Scribe folder into your root NodeJS folder. Note: What I am about to show you is the simplest way to use Scribe.js. Since this library (if you can even call it that), is not insave at all, and it should be very easy to adjust to your liking.
1. Make a Scribe directory
----
```javascript
var scribe = require('scribe');
```
\root
\node_modules
\views
\controllers
\bunchOfOtherFolder...
\scribe <--- Make a folder named "scribe"
app.js
```
2. Add Scribe into this folder
----
```
\scribe <--- Copy the contents of the "src" folder (which you get from this repo) into "scribe".
```
4. Install the required modules
----
```bat
npm install colors
npm install moment
npm install mkdirp
npm install callsite
npm install express // if you want to enable the visual web view
```
5. Logging with Scribe
----
```js
var scribe = require('./scribe');
// Configuration
// --------------
scribe.configure(function(){
scribe.set('app', 'MY_APP_NAME'); // NOTE Best way learn about these settings is
scribe.set('logPath', './scribe'); // Doublecheck // them out for yourself.
scribe.set('defaultTag', 'DEFAULT_TAG');
scribe.set('divider', ':::');
scribe.set('identation', 5); // Identation before console messages
## Documentation
_(Coming soon)_
scribe.set('maxTagLength', 30); // Any tags that have a length greather than
// 30 characters will be ignored
## Examples
_(Coming soon)_
scribe.set('mainUser', 'root'); // Username of the account which is running
// the NodeJS server
});
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
// Create Loggers
// --------------
scribe.addLogger("log", true , true, 'green'); // (name, save to file, print to console,
scribe.addLogger('realtime', true, true, 'underline'); // tag color)
scribe.addLogger('high', true, true, 'magenta');
scribe.addLogger('normal', true, true, 'white');
scribe.addLogger('low', true, true, 'grey');
scribe.addLogger('info', true, true, 'cyan');
## Release History
_(Nothing yet)_
// Express.js
// WARNING: ExpressJS must be installed for this to work
// You also need to start an ExpressJS server in order for
// this to work.
// --------------
app.use(scribe.express.logger(function(req, res){ // Express.js access log
return true; // Filter out any Express messages
}));
// Control Panel
// WARNING: ExpressJS must be installed for this to work
// You also need to start an ExpressJS server in order for
// this to work.
// --------------
app.get('/log', scribe.express.controlPanel()); // Enable web control panel
// Basic logging
// --------------
console.log("[Tagname] Your message"); // [Tagname] Your message
console.realtime("[Tagname] Your message"); // [Tagname] Your message
console.high("[Tagname] Your message "); // [Tagname] Your message
console.normal("[Tagname][]Your message"); // [Tagname] []Your message
console.low("[Tagname]Your message"); // [Tagname] Your message
// Tagging function
// ----------------
console.t("Tagname").log("Your message"); // [Tagname] Your message
console.t("Tagname").log("Your message"); // [Tagname] Your message
console.t("Tagname").log("Your message"); // [Tagname] Your message
// Force use default tag
// ---------------------
console.t().log("Your message"); // [MY_APP_NAME] Your message
// Pass in file name
// -----------------
console.f(__filename).log("Your message"); // [file.js] Your message
// Auto tagging
// ------------
console.log("Your message"); // [invokedFrom.js:25] Your message
// Tag Scoping
// -----------
(function(console){
console.info("yeeha"); // [scoped-tag] yeeha
console.log("yeeha"); // [scoped-tag] yeeha
})(console.t('scoped-tag'));
```
6. Experimental
----
```js
// Simple Testing
// --------------
console.test("Test name").should(5).be(5); // Pretty printed test results
```
Contributors
=======
```
bluejamesbond
```
## License
Copyright (c) 2014 Mathew Kurian
Licensed under the MIT license.

430
index.js Normal file
View file

@ -0,0 +1,430 @@
// Scribe.js (NodeJS)
// Mathew Kurian
// Module dependences
// ---------------------------------
var util = require('util');
var mkdirp = require('mkdirp');
var path = require('path');
var moment = require('moment');
var fs = require('fs');
var stack = require('callsite');
var colors = require('colors');
var self = module.exports;
self.express = {};
// Configuration
// ---------------------------------
var $ = {
app: "scribe.js",
logPath: "./../logs",
mainUser: "root",
maxTagLength: 50,
indentation: 2,
divider: ':::',
defaultUserDir: '_user',
testOutput: function(result, pipes, actual, expected, opts) {
var pipe = result ? 'log' : 'error';
var ne = expected.indexOf("\n") > -1;
var na = actual.indexOf("\n") > -1;
pipes[pipe]((" " + opts + " ").bold.inverse + (result ? " PASSED ".green : " FAILED ".red).bold.inverse);
pipes[pipe](" EXPECTED " [result ? "green" : "red"].bold.inverse + " " + (!ne ? expected : ""));
if (ne) {
pipes[pipe](expected);
}
pipes[pipe](" ACTUAL " [result ? "green" : "red"].bold.inverse + " " + (!na ? actual : ""));
if (na) {
pipes[pipe](actual);
}
}
};
// Active settings
// ---------------------------------
var activeDefaultTag;
var activeUserDir;
var activeDateDir;
var activeDayIso;
var activeDir;
var loggers = {};
var theme = {};
var fsOptions = {
encoding: 'utf8'
};
var __reserved = ["f", "t", "tag", "file", "should", "be", "test", "assert"];
// Cache pipe out
// ---------------------------------
var __stdpipe = (function() {
return console.log;
})();
// Utility functions
// ---------------------------------
var pretty = function(a) {
if (!a) {
return a + "";
}
if (typeof a === 'object') {
return JSON.stringify(a, null, 4);
}
return a.toString();
};
var compress = function(a) {
if (!a) {
return a + "";
}
if (typeof a === 'object') {
return JSON.stringify(a);
}
return a.toString();
};
var tag = function(a) {
return "[" + a + "]";
};
var createDir = function() {
mkdirp.sync(path.normalize($.logPath), 0777 & (~process.umask()));
mkdirp.sync(path.normalize(path.join($.logPath, activeDateDir)), 0777 & (~process.umask()));
mkdirp.sync(activeDir = path.normalize(path.join($.logPath, activeDateDir, activeUserDir)), 0777 & (~process.umask()));
};
var getUser = function() {
try {
activeUserDir = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'].toLowerCase();
activeUserDir = activeUserDir.slice(activeUserDir.lastIndexOf((process.platform === 'win32') ? '\\' : '/') + 1);
} catch (e) {
activeUserDir = $.defaultUserDir;
} finally {
return activeUserDir;
}
};
var validate = function() {
var _activeDayIso = moment().day();
if (activeDayIso !== _activeDayIso) {
activeDayIso = _activeDayIso;
activeDateDir = moment().format('MMM_D_YY').toLowerCase();
return true;
}
return false;
};
function Extender(tag, opts) {
var self = this;
self.tag = tag;
self.opts = opts;
self.do = self.invoke = self.should = function(actual) {
var _actual = compress(actual);
self.expect = self.be = function(expected) {
var _expected = compress(expected);
$.testOutput(_actual === _expected, self, pretty(actual), pretty(expected), self.opts);
return self;
};
return self;
};
}
var spaces = function(sp) {
var s = '';
for (var z = 0; z < sp; z++) {
s += ' ';
}
return s;
};
var stackTag = function(_stack) {
try {
return tag(path.basename(_stack.getFileName()) + ":" + _stack.getLineNumber());
} catch (e) {
return tag(activeDefaultTag);
}
};
// Exports
// ---------------------------------
self.addLogger = function(name, file, console, color) {
if (arguments.length < 4) {
return false;
}
if (__reserved.indexOf(name) > -1) {
throw Error("Reserved pipe - " + name);
}
theme[name] = color;
loggers[name] = {
"file": file,
"console": console
};
colors.setTheme(theme);
addPipe(name);
return true;
};
exports.removeLogger = function(name) {
if (loggers[name]) {
delete loggers[name];
delete console[name];
return true;
}
return false;
};
self.set = function(a, b) {
$[a] = b;
};
self.configure = function(callback) {
var _logPath = $.logPath;
var _activeUserDir = activeUserDir;
if (callback) {
callback();
}
activeDefaultTag = tag($.app.toLowerCase());
activeUserDir = getUser();
if ($.logPath !== _logPath) {
if (_logPath) {
fs.unlink(_logPath, function() {});
}
} else if (_activeUserDir !== activeUserDir) {
if (_activeUserDir) {
fs.unlink(_activeUserDir, function() {});
}
}
validate();
createDir();
};
self.express.logger = function(validate) {
return function(req, res, next) {
if (!validate || validate(req, res)) {
console.info('[%s]%s %s %s %s', "express.js", req.ip.red, req.method.green, req.url.grey, (/mobile/i.test(req.headers['user-agent']) ? 'MOBILE' : 'DESKTOP').yellow);
}
next();
};
};
self.express.webpipe = function() {
self.addLogger('user', true, true, 'magenta');
return function(req, res) {
console.t('scribe.js').user(req.ip.red + " " + req.body.data);
res.send('received');
};
};
// Web Control Panel
// ---------------------------------
var datetemplate = fs.readFileSync(path.join(__dirname, "/log.html"), {
encoding: "utf8"
});
var flatColors = ["#16a085", "#27ae60", "#2980b9", "#8e44ad", "#f39c12", "#d35400", "#c0392b", "#7f8c8d"];
self.express.controlPanel = function() {
return function(req, res) {
var date = req.param('date');
if (!date) {
var datePath = path.normalize(path.join($.logPath));
fs.readdir(datePath, function(err, files) {
if (err) {
console.error(err);
return res.send(err);
}
var loggerDates = "";
for (var i = 0; i < files.length; i++) {
try {
var file = files[i];
var fileSplit = file.split("_");
loggerDates += '<div style="background:' +
flatColors[Math.floor(Math.random() * flatColors.length)] + '"data-types="' +
fs.readdirSync(path.join(datePath, file, $.mainUser)).join(',').replace(/app./g, '') + '", data-raw="' +
file + '" class="date"><div class="date-month">' + fileSplit[0] + '</div><div class="date-day">' +
fileSplit[1] + '</div><div class="date-year">' + ("20" + fileSplit[2]) + '</div></div>';
} catch (e) {
console.error(e);
return res.send(e);
}
}
return res.send(datetemplate.replace("__title", $.app + " - Scribe.js Control Panel")
.replace('__content', files.join(","))
.replace('__logdates', loggerDates)
.replace('__logpath', activeDir)
.replace('__username', $.mainUser)
.replace('__divider', $.divider));
});
return;
}
var type = req.param('type');
type = type ? type : "log";
var filepath = path.join(activeDir, "app." + type);
if (fs.existsSync(filepath)) {
var stream = fs.createReadStream(filepath);
res.writeHead(200, {
'Content-Length': fs.statSync(filepath).size,
'Content-Type': 'text/plain',
});
stream.pipe(res);
} else {
res.statusCode = 404;
res.send();
}
};
};
// Additional Features
// ---------------------------------
console.t = console.tag = function(n) {
return new Extender(n ? tag(n) : activeDefaultTag);
};
console.f = console.file = function(n) {
var _tag;
if (!n) {
var st = stack()[1];
_tag = tag(path.basename(st.getFileName()) + ":" + st.getLineNumber());
} else {
_tag = tag(path.basename(n));
}
return new Extender(_tag);
};
console.assert = console.test = function(name, tag) {
tag = tag ? tag : stackTag(stack()[1]);
return new Extender(tag, name, stack()[1]);
};
function addPipe(n) {
Extender.prototype[n] = function() {
var args = Array.prototype.splice.call(arguments, 0);
args.unshift(this.tag + args.shift());
console[n].apply(this, args);
};
console[n] = (function(i) {
if (validate()) {
createDir();
}
return function() {
var utfs = (arguments.length === 1 ? pretty(arguments[0]) : util.format.apply(util, arguments)).trim();
var time = moment().format('h:mm:ss A');
var file = path.join(activeDir, 'app.' + i);
var indent = spaces($.indentation);
var tag = utfs.match(/^\[(.*?)\]\s{0,}/m);
var cleanTag;
if (loggers[i].file && utfs) {
var outfs = utfs.stripColors;
cleanTag = "";
if (tag) {
outfs = outfs.replace(tag[0], "");
cleanTag = tag[0].trim();
}
outfs = time + $.divider + cleanTag + outfs.replace(/\n/g, '\n' + time + $.divider + cleanTag) + '\n';
fs.appendFileSync(file, outfs, fsOptions, function() {});
}
if (loggers[i].console) {
if (!tag) {
tag = [stackTag(stack()[1])];
}
var tabIn;
cleanTag = tag[0].trim();
if (cleanTag.length <= $.maxTagLength) {
utfs = utfs.replace(tag[0], "");
tabIn = spaces($.maxTagLength - cleanTag.length);
cleanTag = cleanTag[i].bold;
utfs = indent + cleanTag + tabIn + utfs.replace(/\n/g, '\n' + indent + cleanTag + tabIn);
} else {
tabIn = indent + spaces($.maxTagLength);
utfs = tabIn + utfs.replace(/\n/g, '\n' + tabIn);
}
__stdpipe(utfs);
}
};
})(n);
// console.t()[n]('Created pipe console.%s', n.toUpperCase());
}
// Startup
$.mainUser = activeUserDir = getUser();
self.configure();
// Express missing notification
try {
var express = require("express");
if (!express) {
throw new Error();
}
} catch (e) {
console.warn("SCRIBE WARNING: Express not installed - visual web logger is disabled.");
}

50
package.json Normal file
View file

@ -0,0 +1,50 @@
{
"name": "Scribe.js",
"description": "Unlike many of the libraries out there, Scribe.js allows logging on multiple files and is divided into folders by date. And it is possibly the easiest logging you can implement. And it does everything you need a basic logger to do.",
"version": "0.1.0",
"homepage": "https://github.com/bluejamesbond/Scribe.js",
"keywords": [],
"author": "Mathew Kurian <MathewKurian@utexas.edu> (https://github.com/bluejamesbond)",
"repository": {
"type": "git",
"url": "git://github.com/bluejamesbond/Scribe.js.git"
},
"bugs": {
"url": "https://github.com/bluejamesbond/Scribe.js/issues"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/bluejamesbond/Scribe.js/blob/master/LICENSE-MIT"
}
],
"main": "index.js",
"engines": {
"node": "0.10.29"
},
"scripts": {
"test": "grunt nodeunit"
},
"devDependencies": {
"grunt-contrib-jshint": "~0.6.4",
"grunt-contrib-nodeunit": "~0.2.0",
"grunt-contrib-watch": "~0.5.3",
"grunt": "~0.4.5"
},
"directories": {
"test": "test"
},
"license": "MIT",
"dependencies": {
"callsite": "^1.0.0",
"colors": "^0.6.2",
"express": "^4.7.2",
"grunt": "^0.4.5",
"grunt-contrib-jshint": "^0.10.0",
"grunt-cli": "^0.1.13",
"grunt-contrib-nodeunit": "^0.4.1",
"grunt-contrib-watch": "^0.6.1",
"mkdirp": "^0.5.0",
"moment": "^2.8.0"
}
}

View file

@ -1,425 +0,0 @@
// Scribe.js (NodeJS)
// Copyright 2014 by Mathew Kurian
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT SPLICEED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Module dependences
// ---------------------------------
var util = require('util');
var mkdirp = require('mkdirp');
var path = require('path');
var moment = require('moment');
var fs = require('fs');
var stack = require('callsite');
var colors = require('colors');
var self = module.exports;
self.express = {};
// Configuration
// ---------------------------------
var $ = {
app : "scribe.js",
logPath : "./../logs",
mainUser : "root",
maxTagLength : 50,
indentation : 2,
divider : ':::',
defaultUserDir : '_user',
testOutput : function(result, pipes, actual, expected, opts){
var pipe = result ? 'log' : 'error';
var ne = expected.indexOf("\n") > -1;
var na = actual.indexOf("\n") > -1;
pipes[pipe]((" " + opts + " ").bold.inverse + (result ? " PASSED ".green : " FAILED ".red).bold.inverse)
pipes[pipe](" EXPECTED "[result ? "green" : "red"].bold.inverse + " " + (!ne ? expected: ""))
if(ne) pipes[pipe](expected);
pipes[pipe](" ACTUAL "[result ? "green" : "red"].bold.inverse + " " + (!na ? actual : ""))
if(na) pipes[pipe](actual);
}
}
// Active settings
// ---------------------------------
var activeDefaultTag;
var activeUserDir;
var activeDateDir;
var activeDayIso;
var activeDir;
var loggers = {};
var theme = {};
var fsOptions = { encoding : 'utf8' }
var __reserved = [ "f", "t", "tag", "file", "should", "be", "test", "assert" ];
// Cache pipe out
// ---------------------------------
var __stdpipe = (function(){
return console.log;
})();
// Utility functions
// ---------------------------------
var pretty = function(a){
if(!a) return a + "";
if(typeof a === 'object')
return JSON.stringify(a, null, 4);
return a.toString();
}
var compress = function(a){
if(!a) return a + "";
if(typeof a === 'object')
return JSON.stringify(a);
return a.toString();
}
var tag = function(a){
return "[" + a + "]";
}
var createDir = function(){
mkdirp.sync(path.normalize($.logPath), 0777 & (~process.umask()));
mkdirp.sync(path.normalize(path.join($.logPath, activeDateDir)), 0777 & (~process.umask()));
mkdirp.sync(activeDir = path.normalize(path.join($.logPath, activeDateDir, activeUserDir)), 0777 & (~process.umask()));
}
var getUser = function(){
try {
activeUserDir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'].toLowerCase();
activeUserDir = activeUserDir.slice(activeUserDir.lastIndexOf((process.platform == 'win32') ? '\\':'/') + 1);
} catch(e){
activeUserDir = $.defaultUserDir;
} finally {
return activeUserDir;
}
}
var validate = function(){
var _activeDayIso = moment().day();
if(activeDayIso != _activeDayIso) {
activeDayIso = _activeDayIso;
activeDateDir = moment().format('MMM_D_YY').toLowerCase();
return true;
}
return false;
}
function Extender(tag, opts, stack){
var self = this;
self.tag = tag;
self.opts = opts;
self.do = self.invoke = self.should = function(actual){
var _actual = compress(actual);
self.expect = self.be = function(expected){
var _expected = compress(expected);
$.testOutput(_actual === _expected, self, pretty(actual), pretty(expected), self.opts);
return self;
}
return self;
}
}
var spaces = function(sp){
var s = '';
for(var z = 0; z < sp; z++)
s += ' ';
return s;
}
var stackTag = function(_stack){
try {
return tag(path.basename(_stack.getFileName()) + ":" + _stack.getLineNumber());
} catch(e){
return tag(activeDefaultTag);
}
}
// Exports
// ---------------------------------
self.addLogger = function(name, file, console, color){
if(arguments.length < 4)
return false;
if(__reserved.indexOf(name) > -1)
throw Error("Reserved pipe - " + name);
theme[name] = color;
loggers[name] = {
"file" : file,
"console" : console
}
colors.setTheme(theme);
addPipe(name);
return true;
}
exports.removeLogger = function(name){
if(loggers[name]) {
delete loggers[name];
delete console[name];
return true;
}
return false;
}
self.set = function(a, b){
$[a] = b;
}
self.configure = function(callback){
var _logPath = $.logPath;
var _activeUserDir = activeUserDir;
if(callback) callback();
activeDefaultTag = tag($.app.toLowerCase());
activeUserDir = getUser();
if($.logPath !== _logPath){
if(_logPath) fs.unlink(_logPath, function(){})
} else if (_activeUserDir !== activeUserDir){
if(_activeUserDir) fs.unlink(_activeUserDir, function(){})
}
validate();
createDir();
}
self.express.logger = function(validate) {
return function(req, res, next){
if(!validate || validate(req, res)) {
console.info('[%s]%s %s %s %s' , "express.js"
, req.ip.red
, req.method.green
, req.url.grey
, (/mobile/i.test(req.headers['user-agent']) ? 'MOBILE' : 'DESKTOP').yellow);
}
next();
}
}
self.express.webpipe = function(){
self.addLogger('user', true, true, 'magenta');
return function(req, res){
console.t('scribe.js').user(req.ip.red + " " + req.body.data);
res.send('received');
};
}
// Web Control Panel
// ---------------------------------
var datetemplate = fs.readFileSync(path.join(__dirname, "/log.html"), { encoding : "utf8"});
var flatColors = [ "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#f39c12", "#d35400", "#c0392b", "#7f8c8d"]
self.express.controlPanel = function() {
return function(req, res){
var date = req.param('date');
if(!date) {
var logs = [];
var datePath = path.normalize(path.join($.logPath));
fs.readdir(datePath, function(err, files){
var response;
var loggerDates = "";
for(var i = 0; i < files.length; i++){
try {
var file = files[i];
var fileSplit = file.split("_");
loggerDates += '<div style="background:' +
flatColors[Math.floor(Math.random() * flatColors.length)] + '"data-types="' +
fs.readdirSync(path.join(datePath, file, $.mainUser)).join(',').replace(/app./g, '') + '", data-raw="' +
file + '" class="date"><div class="date-month">' + fileSplit[0] + '</div><div class="date-day">' +
fileSplit[1] + '</div><div class="date-year">' + ("20" + fileSplit[2]) + '</div></div>';
} catch(e) {}
}
return res.send(datetemplate.replace("__title", $.app + " - Scribe.js Control Panel")
.replace('__content', files.join(","))
.replace('__logdates', loggerDates)
.replace('__logpath', activeDir)
.replace('__username', $.mainUser)
.replace('__divider', $.divider));
});
return;
}
var type = req.param('type');
type = type ? type : "log";
var contents = "No log found";
var filepath = path.join(activeDir, "app." + type);
if(fs.existsSync(filepath)){
var stream = fs.createReadStream(filepath);
res.writeHead(200, {
'Content-Length': fs.statSync(filepath)["size"],
'Content-Type': 'text/plain',
});
stream.pipe(res);
} else{
res.statusCode = 404;
res.send();
}
}
}
// Additional Features
// ---------------------------------
console['t'] = console['tag'] = function(n){
return new Extender(n ? tag(n) : activeDefaultTag);
}
console['f'] = console['file'] = function(n){
var _tag;
if(!n) {
var st = stack()[1];
_tag = tag(path.basename(st.getFileName()) + ":" + st.getLineNumber());
} else {
_tag = tag(path.basename(n));
}
return new Extender(_tag);
}
console['assert'] = console['test'] = function(name, tag){
tag = tag ? tag : stackTag(stack()[1]);
return new Extender(tag, name, stack()[1]);
}
var addPipe = function(n) {
Extender.prototype[n] = function(){
var args = Array.prototype.splice.call(arguments, 0);
args.unshift(this.tag + args.shift());
console[n].apply(this, args);
}
console[n] = (function (i) {
if(validate()){
createDir();
}
return function () {
var utfs = (arguments.length == 1 ? pretty(arguments[0]) : util.format.apply(util, arguments)).trim();
var time = moment().format('h:mm:ss A')
var file = path.join(activeDir, 'app.' + i )
var indent = spaces($.indentation);
var tag = utfs.match(/^\[(.*?)\]\s{0,}/m);
if(loggers[i].file && utfs != ''){
var outfs = utfs.stripColors;
var cleanTag = "";
if(tag) {
outfs = outfs.replace(tag[0], "");
cleanTag = tag[0].trim();
}
outfs = time + $.divider + cleanTag + outfs.replace(/\n/g, '\n' + time + $.divider + cleanTag) + '\n';
fs.appendFileSync(file, outfs, fsOptions, function(err){});
}
if (loggers[i].console){
if(!tag) {
tag = [ stackTag(stack()[1]) ];
}
var tabIn;
var cleanTag = tag[0].trim();
if(cleanTag.length <= $.maxTagLength){
utfs = utfs.replace(tag[0], "");
tabIn = spaces($.maxTagLength - cleanTag.length);
cleanTag = cleanTag[i].bold;
utfs = indent + cleanTag + tabIn + utfs.replace(/\n/g, '\n' + indent + cleanTag + tabIn);
} else {
tabIn = indent + spaces($.maxTagLength);
utfs = tabIn + utfs.replace(/\n/g, '\n' + tabIn);
}
__stdpipe(utfs);
}
}
})(n);
// console.t()[n]('Created pipe console.%s', n.toUpperCase());
}
// Startup
activeUserDir = getUser();
self.configure();
// Express missing notification
try {
var express = require("express");
if(!express){
throw new Error();
}
} catch(e){
console.warn("SCRIBE WARNING: Express not installed - visual web logger is disabled.");
}

117
test/express-usage.js Normal file
View file

@ -0,0 +1,117 @@
'use strict';
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
var scribe = require('../');
var express = require('express');
var app = express();
exports['read'] = {
"to-obj": function(test) {
test.expect(1);
// Configuration
// --------------
scribe.configure(function() {
scribe.set('app', 'MY_APP_NAME'); // NOTE Best way learn about these settings is
scribe.set('logPath', './test/logs'); // Doublecheck // them out for yourself.
scribe.set('defaultTag', 'DEFAULT_TAG');
scribe.set('divider', ':::');
scribe.set('identation', 5); // Identation before console messages
scribe.set('maxTagLength', 30); // Any tags that have a length greather than
// 30 characters will be ignored
// scribe.set('mainUser', 'root'); // Username of the account which is running
// the NodeJS server
});
// Create Loggers
// --------------
scribe.addLogger("log", true, true, 'green'); // (name, save to file, print to console,
scribe.addLogger('realtime', true, true, 'underline'); // tag color)
scribe.addLogger('high', true, true, 'magenta');
scribe.addLogger('normal', true, true, 'white');
scribe.addLogger('low', true, true, 'grey');
scribe.addLogger('info', true, true, 'cyan');
// Express.js
// WARNING: ExpressJS must be installed for this to work
// You also need to start an ExpressJS server in order for
// this to work.
// --------------
app.use(scribe.express.logger(function(req, res) { // Express.js access log
return true; // Filter out any Express messages
}));
// Control Panel
// WARNING: ExpressJS must be installed for this to work
// You also need to start an ExpressJS server in order for
// this to work.
// --------------
app.get('/log', scribe.express.controlPanel()); // Enable web control panel
var server = app.listen(2000, function() {
console.log('Listening on port %d', server.address().port);
});
// Basic logging
// --------------
console.log("[Tagname] Your message"); // [Tagname] Your message
console.realtime("[Tagname] Your message"); // [Tagname] Your message
console.high("[Tagname] Your message "); // [Tagname] Your message
console.normal("[Tagname][]Your message"); // [Tagname] []Your message
console.low("[Tagname]Your message"); // [Tagname] Your message
// Tagging function
// ----------------
console.t("Tagname").log("Your message"); // [Tagname] Your message
console.t("Tagname").log("Your message"); // [Tagname] Your message
console.t("Tagname").log("Your message"); // [Tagname] Your message
// Force use default tag
// ---------------------
console.t().log("Your message"); // [MY_APP_NAME] Your message
// Pass in file name
// -----------------
console.f(__filename).log("Your message"); // [file.js] Your message
// Auto tagging
// ------------
console.log("Your message"); // [invokedFrom.js:25] Your message
// Tag Scoping
// -----------
(function(console) {
console.info("yeeha"); // [scoped-tag] yeeha
console.log("yeeha"); // [scoped-tag] yeeha
})(console.t('scoped-tag'));
console.warn("For the web view...");
console.warn("Please visit http://localhost:2000/log");
// test.equal(true, true);
// test.done();
}
};

93
test/usage.js Normal file
View file

@ -0,0 +1,93 @@
'use strict';
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
var scribe = require('../');
exports['read'] = {
"to-obj": function(test) {
test.expect(1);
// Configuration
// --------------
scribe.configure(function() {
scribe.set('app', 'MY_APP_NAME'); // NOTE Best way learn about these settings is
scribe.set('logPath', './test/logs'); // Doublecheck // them out for yourself.
scribe.set('defaultTag', 'DEFAULT_TAG');
scribe.set('divider', ':::');
scribe.set('identation', 5); // Identation before console messages
scribe.set('maxTagLength', 30); // Any tags that have a length greather than
// 30 characters will be ignored
// scribe.set('mainUser', 'root'); // Username of the account which is running
// the NodeJS server
});
// Create Loggers
// --------------
scribe.addLogger("log", true, true, 'green'); // (name, save to file, print to console,
scribe.addLogger('realtime', true, true, 'underline'); // tag color)
scribe.addLogger('high', true, true, 'magenta');
scribe.addLogger('normal', true, true, 'white');
scribe.addLogger('low', true, true, 'grey');
scribe.addLogger('info', true, true, 'cyan');
// Basic logging
// --------------
console.log("[Tagname] Your message"); // [Tagname] Your message
console.realtime("[Tagname] Your message"); // [Tagname] Your message
console.high("[Tagname] Your message "); // [Tagname] Your message
console.normal("[Tagname][]Your message"); // [Tagname] []Your message
console.low("[Tagname]Your message"); // [Tagname] Your message
// Tagging function
// ----------------
console.t("Tagname").log("Your message"); // [Tagname] Your message
console.t("Tagname").log("Your message"); // [Tagname] Your message
console.t("Tagname").log("Your message"); // [Tagname] Your message
// Force use default tag
// ---------------------
console.t().log("Your message"); // [MY_APP_NAME] Your message
// Pass in file name
// -----------------
console.f(__filename).log("Your message"); // [file.js] Your message
// Auto tagging
// ------------
console.log("Your message"); // [invokedFrom.js:25] Your message
// Tag Scoping
// -----------
(function(console) {
console.info("yeeha"); // [scoped-tag] yeeha
console.log("yeeha"); // [scoped-tag] yeeha
})(console.t('scoped-tag'));
test.equal(true, true);
test.done();
}
};