問題:線上的寫日誌操做很是頻繁,想統計每秒寫了多少行數據?假如無法送一個消息寫一個日誌,問題也就變成了,每秒發送多少消息了。函數
日誌採用log4js書寫,格式以下:ui
[2014-03-10 11:23:33.548] [INFO] lac - [2014-03-10 11:23:33.551] [INFO] lac - [2014-03-10 11:23:33.563] [INFO] lac - [2014-03-10 11:23:33.569] [INFO] lac - [2014-03-10 11:23:33.572] [INFO] lac -
思路:依次讀取日誌的每一行,解析出時間字段,如 11:23:33 做爲一個哈希表的key,沒碰到依次,統計值加1. 最後根據統計次數排序。spa
1)按行讀取:使用readline模塊,在createInterface函數中將已經建立的readStream對象傳遞給他便可。日誌
2)監聽readline模塊的line事件,在其中能夠讀到每一行數據code
3)監聽close事件,當文件讀取完成時會獲得通知,在其中進行排序操做。對象
4)完成blog
代碼以下:排序
var readline = require('readline'); var fs = require('fs');
if(process.argv.length != 3)
{
console.log("parameter: file.log");
return;
}事件
var logFile = process.argv[2];terminal
var file = fs.createReadStream(logFile); var rl = readline.createInterface({ input: file, output: process.stdout, terminal: false }); var counter = {}; rl.on('line',function(line){ var items = line.split(' '); if(items.length >= 2){ console.log("%s",items[1].substring(0,8)); var timestr = items[1].substring(0,8); if(counter.hasOwnProperty(timestr)){ counter[timestr]++; }else{ counter[timestr] = 1; } } }); rl.on('close',function(){ rl.close(); file.close(); var keys = Object.keys(counter); var arr = []; for(var index in keys){ var key = keys[index]; arr.push({count:counter[key],key:key}); } ///sort by count descent arr.sort(function(item1,item2){ return item2.count - item1.count; }); for(var index in arr){ console.log('%s %d',arr[index].key,arr[index].count); } });