Advertisement
Guest User

Node.JS console to file

a guest
Jun 6th, 2013
892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //DO NOT PUT "use strict" HERE OR THE LOGGER WILL NOT BE ABLE TO LOG ERROR
  2. /* ************************************************************************
  3.  
  4.         Version: 0.3
  5.  
  6.         License: LGPLv3
  7.  
  8.         Authors: Deisss
  9.  
  10.         Date: 2012-04-20
  11.  
  12.         Date of last modification: 2013-06-07
  13.  
  14.         Description: Define a shared stdout/stderror shared redirection
  15.  
  16. ************************************************************************ */
  17.  
  18. // Module loaded
  19. var fs   = require("fs"),
  20.     util = require("util");
  21.  
  22. // Variables, do not forget / at then end !
  23. var windows_error_log_root = __dirname + "/../",
  24.     unix_error_log_root    = "/var/log/node/",
  25.  
  26.     max_line_number        = 10000,
  27.     stdout                 = null,
  28.     stderr                 = null,
  29.     stdoutPath             = "",
  30.     stderrPath             = "",
  31.     maxct                  = max_line_number;
  32.  
  33. /*
  34. --------------------------------------
  35.   TIME FUNCTION
  36. --------------------------------------
  37. */
  38. /**
  39.  * Print a date with "0" before if it's less than 10
  40.  *
  41.  * @param variable {Integer} A number (from date)
  42.  * @return {String} The parsed date
  43. */
  44. function beautifulDate(variable) {
  45.     var prefix = (variable < 10) ? "0" : "";
  46.     return prefix + variable;
  47. };
  48.  
  49. /**
  50.  * Print in a nice way the output date
  51.  *
  52.  * @return {String} The formatted date
  53. */
  54. function outputDate() {
  55.     var d = new Date();
  56.     return ("" + d.getFullYear() + "-" + beautifulDate(d.getMonth()+1) + "-" + beautifulDate(d.getDate()) + "   " +
  57.         beautifulDate(d.getHours()) + "." + beautifulDate(d.getMinutes()) + "." + beautifulDate(d.getSeconds()));
  58. };
  59.  
  60. /**
  61.  * Return a formatted date string
  62.  *
  63.  * @return {String} The formatted date
  64. */
  65. var printDate = function() {
  66.     var d = new Date();
  67.     var tmp = outputDate();
  68.     return (tmp.replace(".", ":") + "   (UTC : " + (d.getTimezoneOffset()/60) + "h) => ");
  69. };
  70.  
  71. /*
  72. --------------------------------------
  73.   PATH FUNCTION
  74. --------------------------------------
  75. */
  76. /**
  77.  * Get the main OS path, create it if needed
  78. */
  79. function getOSRootPath() {
  80.     var path = "";
  81.     if(process.platform === "win32") {
  82.         path = windows_error_log_root;
  83.     } else {
  84.         path = unix_error_log_root;
  85.     }
  86.  
  87.     //Test or create the directory, we do it synchronously to never loose any log message
  88.     try {
  89.         if(!fs.statSync(windows_error_log_root).isDirectory()) {
  90.             fs.mkdirSync(windows_error_log_root, 0600);
  91.         }
  92.     } catch(e) {
  93.         fs.mkdirSync(windows_error_log_root, 0600);
  94.     }
  95.  
  96.     return path;
  97. };
  98.  
  99. /*
  100. --------------------------------------
  101.   STREAM FUNCTION
  102. --------------------------------------
  103. */
  104. /**
  105.  * Start log stream system
  106. */
  107. function createStream() {
  108.     var path = getOSRootPath();
  109.  
  110.     stdoutPath = path + "access.log";
  111.     stderrPath = path + "error.log";
  112.     stdout = fs.createWriteStream(stdoutPath, { flags: "a" });
  113.     stderr = fs.createWriteStream(stderrPath, { flags: "a" });
  114. };
  115.  
  116. /**
  117.  * Close log stream system
  118. */
  119. function closeStream() {
  120.     stdout.end();
  121.     stderr.end();
  122. };
  123.  
  124. /**
  125.  * Close stream if needed
  126. */
  127. function checkAndCloseStream() {
  128.     maxct--;
  129.     if(maxct <= 0) {
  130.         closeStream();
  131.  
  132.         //Now we move log files to something usable
  133.         var d = outputDate();
  134.         fs.renameSync(stdoutPath, getOSRootPath() + "access-" + d + ".log");
  135.         fs.renameSync(stderrPath, getOSRootPath() + "error-" + d + ".log");
  136.  
  137.         //Now we create again stream
  138.         createStream();
  139.         maxct = max_line_number;
  140.     }
  141. };
  142.  
  143. /**
  144.  * Console logger object
  145. */
  146. module.exports = new function() {
  147.     /**
  148.      * Print a log (any number of arguments allowed)
  149.     */
  150.     this.log = function() {
  151.         console.log.apply(this, arguments);
  152.         if(stdout != null && stdout.writable===true) {
  153.             stdout.write(printDate() + util.format.apply(this, arguments) + "\n");
  154.             checkAndCloseStream();
  155.         }
  156.     };
  157.  
  158.     /**
  159.      * Print dir (any number of arguments allowed)
  160.     */
  161.     this.dir = function(object) {
  162.         console.dir.apply(this, arguments);
  163.         if(stdout != null && stdout.writable===true) {
  164.             stdout.write(printDate() + util.inspect(object) + "\n");
  165.             checkAndCloseStream();
  166.         }
  167.     };
  168.  
  169.     /**
  170.      * Print an error (any number of arguments allowed)
  171.     */
  172.     this.error = function() {
  173.         console.error.apply(this, arguments);
  174.         if(stderr != null && stderr.writable===true) {
  175.             stderr.write(printDate() + util.format.apply(this, arguments) + "\n");
  176.             checkAndCloseStream();
  177.         }
  178.     };
  179.     // Alias
  180.     this.err = this.error;
  181.  
  182.     //Catching all system error
  183.     process.on("uncaughtException", function(err) {
  184.         this.error("Uncaught exception : ");
  185.         this.error(err);
  186.     }.bind(this));
  187.  
  188.     //We create the stream
  189.     createStream();
  190. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement