Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Example/demonstration of log-file rotation.

  • Loading branch information...
commit fa0c9b6a4e250abe9c301ee1a3214ceb6bdc2f8a 1 parent f4b5a43
@thakkar-rushikesh authored
Showing with 53 additions and 0 deletions.
  1. +10 −0 Readme.md
  2. +43 −0 examples/file-rotate.js
View
10 Readme.md
@@ -33,6 +33,16 @@ Instead of the log level constants, you may also supply a string:
We can also use `%s` much like `console.log()` to pass arguments:
log.error('oh no, failed to send mail to %s.', user.email);
+
+When using file stream, you can specify rotation-time (as hour-of-the-day in 24hrs format) to rotate the log file:
+
+ var fs = require('fs')
+ , Log = require('log')
+ var stream = fs.createWriteStream('/path/to/my-node.log');
+ var log = new Log('debug', stream, {rotate:true, rotationTime:23});
+
+This will emit `rotate` event at the specified hour of the day. In the above example, `rotate` event will be emitted at 11:00 PM.
+You need to handle `rotate` event to actually rotate the file. An example is provided here: `examples\file-rotate.js`.
## Reader
View
43 examples/file-rotate.js
@@ -0,0 +1,43 @@
+var fs = require('fs');
+var Log = require('log');
+var logger;
+
+function formatDate(dt) {
+ var month = dt.getMonth() + 1;
+ month = (month < 10) ? ('0'+month) : month;
+ var date = dt.getDate();
+ date = (date < 10) ? ('0'+date) : date;
+ var strDate = dt.getFullYear() + '-' + month + '-' + date; //yyyy-MM-dd
+ return strDate;
+}
+
+function initializeLog(logFileName) {
+ var stream = fs.createWriteStream(logFileName, {flags: 'a+', mode:0777});
+ logger = new Log('debug', stream, {rotate:true, rotationTime:20});
+ logger.on('rotate', function (rotateTime) {
+ logger.info('Time to Rotate the log file: ' + rotateTime);
+ strDate = formatDate(rotateTime);
+ console.log(strDate);
+ stream.destroy();
+
+ stream.on('close', function(){
+ fs.rename(logFileName, logFileName+'.'+strDate, function(){
+ console.log('Re-initializing logger.');
+ initializeLog(logFileName);
+ });
+ });
+ stream.on('error', function(err){
+ console.log('Error: ' + err);
+ });
+ });
+}
+
+initializeLog('/var/log/node/node.log');
+
+logger.debug('Counting Stars on this bright sunny day!');
+var i = 1;
+setInterval(function() {
+ console.log('Star: ' + i);
+ logger.debug('Star: ' + i);
+ i++;
+}, 2000);

0 comments on commit fa0c9b6

Please sign in to comment.
Something went wrong with that request. Please try again.