summaryrefslogtreecommitdiff
path: root/logger.js
blob: 592342d4bd072e506b91b0094144a160bad2bcda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var fs=require("fs");

var MAX_VOLUME=16*1024*1024;

function Logger(fname){
	if(!(this instanceof Logger))throw new Error("Logger() called without 'new'");
	this._fname=fname;
	this._logstart=new Date();
	this._currentfname=fname+"."+this._logstart.getTime();
	this._volume=0;
	this._stream=fs.createWriteStream(this._currentfname);
	this._ok=true;
}

Logger.prototype.log=function log(line){
	if(!this._ok)return;
	var now=new Date();
	var data=now.toISOString()+": "+line+"\n";
	if(this._volume+data.length>MAX_VOLUME){
		this._stream.end();
		this._logstart=now;
		this._currentfname=this._fname+"."+this._logstart.getTime();
		this._volume=0;
		this._stream=fs.createWriteStream(this._currentfname);
		this._ok=true;
	}
	this._volume+=data.length;
	if(!this._stream.write(data)){
		console.log("WARNING: LOG STREAM '"+this._currentfname+"' NOT DRAINING!");
		this._ok=false;
		this._stream.once("drain",function(){this._ok=true;}.bind(this));
	}
};

module.exports=Logger;