forked from logdna/nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
171 lines (149 loc) · 5.17 KB
/
logger.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
* LogDNA NPM Module
* - supports levels (Debug, Info, Notice, Warning, Error, Critical, Alert, Emerge)
* - supports winston
*/
var sizeof = require('object-sizeof');
var configs = require('./configs');
var request = require('request');
var util = require('util');
var debug = util.debuglog('logdna');
var stringify = require('json-stringify-safe');
var _ = require('lodash');
var os = require('os');
function isInt(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value));
}
function checkParam(param, name, optional) {
if (optional && !param) return;
if (!param || !_.isString(param)) {
throw new Error(name + ' is undefined or not passed as a String');
} else if (param.length > configs.MAX_INPUT_LENGTH) {
throw new Error(name + ' cannot be longer than ' + configs.MAX_INPUT_LENGTH + ' chars');
}
}
function Logger(key, options) {
if (!(this instanceof Logger)) return new Logger(key, options);
checkParam(key, 'LogDNA API Key', false);
checkParam(options.hostname, 'Hostname', true);
checkParam(options.mac, 'MAC Address', true);
checkParam(options.ip, 'IP Address', true);
checkParam(options.level, 'Level', true);
checkParam(options.app, 'App', true);
if (options.timeout) {
if (!isInt(options.timeout)) {
throw new Error('Timeout must be an Integer');
}
if (options.timeout > configs.MAX_REQUEST_TIMEOUT) {
throw new Error('Timeout cannot be longer than' + configs.MAX_REQUEST_TIMEOUT);
}
}
if (options.mac && !configs.MAC_ADDR_CHECK.test(options.mac)) {
throw new Error('Invalid MAC Address format');
}
if (options.ip && !configs.IP_ADDR_CHECK.test(options.ip)) {
throw new Error('Invalid IP Address format');
}
this._flushLimit = configs.FLUSH_BYTE_LIMIT;
this._url = configs.LOGDNA_URL;
var protocol = configs.AGENT_PROTOCOL;
this._agent = new protocol(configs.AGENT_SETTING);
this._bufByteLength = 0;
this._buf = [];
this._err;
this.source = {
hostname: options.hostname || os.hostname(),
app: options.app || 'default',
level: options.level || 'Info'
};
this._req = request.defaults({
auth: { username: key },
agent: this._agent,
headers: configs.DEFAULT_REQUEST_HEADER,
qs: {
hostname: this.source.hostname,
mac: options.mac,
ip: options.ip
},
timeout: options.timeout || configs.DEFAULT_REQUEST_TIMEOUT
});
}
Logger.prototype.log = function(statement, opts) {
this._err = false;
if (typeof statement === 'object') {
statement = stringify(statement, null, 2, function() { return undefined; });
}
var message = {
timestamp: Date.now(),
line: statement,
level: this.source.level,
app: this.source.app
};
if (opts) {
if (_.isString(opts)) {
if (opts.length > configs.MAX_INPUT_LENGTH) {
debug('Level had more than ' + configs.MAX_INPUT_LENGTH + ' chars, was truncated');
opts = opts.substring(0, configs.MAX_INPUT_LENGTH);
}
message.level = opts;
} else {
if (typeof opts != 'object') {
this._err = true;
debug('Can only pass a String or JSON object as additional parameter');
}
message.level = opts.level || message.level;
message.app = opts.app || message.app;
}
}
if (this._err) {
return this._err;
}
this._bufferLog(message);
};
Logger.prototype._bufferLog = function(message) {
if (!message || !message.line) return;
if (message.line.length > configs.MAX_LINE_LENGTH) {
message.line = message.line.substring(0, configs.MAX_LINE_LENGTH) + ' (cut off, too long...)';
debug('Line was longer than ' + configs.MAX_LINE_LENGTH + ' chars and was truncated.');
}
this._bufByteLength += sizeof(message);
// this._bufLength += getBytes(JSON.stringify(message));
this._buf.push(message);
if (this._bufByteLength >= this._flushLimit) {
this._flush();
return;
}
if (!this._flusher) {
this._flusher = setTimeout(_.bind(this._flush, this), configs.FLUSH_INTERVAL);
}
};
Logger.prototype._flush = function() {
if (!this._req || this._buf.length === 0) { return; }
var sendbuf = { e: 'ls', ls: this._buf };
var data = JSON.stringify(sendbuf);
this._bufByteLength = 0;
this._buf.length = 0;
this._req.post(this._url, {
body: data,
qs: { now: Date.now() }
}, function(err) {
if (err) { debug('Encountered an Error in POST Request: %j', err); }
});
clearTimeout(this._flusher);
this._flusher = null;
};
/*
* Populate short-hand for each supported Log Level
*/
_.forEach(configs.LOG_LEVELS, function(level) {
var l = level.toLowerCase();
Logger.prototype[l] = function(statement, opts) {
opts = opts || {};
opts.level = level;
this.log(statement, opts);
};
});
exports.Logger = Logger;
exports.createLogger = function(key, options) {
return new Logger(key, options);
};