This repository has been archived by the owner on Jan 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
graylog.js
196 lines (164 loc) · 5.21 KB
/
graylog.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
var
zlib = require('zlib'),
dgram = require('dgram'),
util = require('util'),
dns = require('dns'),
net = require('net');
GLOBAL.LOG_EMERG=0; // system is unusable
GLOBAL.LOG_ALERT=1; // action must be taken immediately
GLOBAL.LOG_CRIT=2; // critical conditions
GLOBAL.LOG_ERR=3; // error conditions
GLOBAL.LOG_ERROR=3; // because people WILL typo
GLOBAL.LOG_WARNING=4; // warning conditions
GLOBAL.LOG_NOTICE=5; // normal, but significant, condition
GLOBAL.LOG_INFO=6; // informational message
GLOBAL.LOG_DEBUG=7; // debug-level message
GLOBAL.graylogHost = 'localhost';
GLOBAL.graylogPort = 12201;
GLOBAL.graylogHostname = require('os').hostname();
GLOBAL.graylogToConsole = false;
GLOBAL.graylogFacility = 'Node.js';
GLOBAL.graylogSequence = 0;
GLOBAL.graylogChunkSize = 1100; // 8192 is the maximum
GLOBAL.graylogAdditionalFields = {};
GLOBAL.gelfVersion = 1.1
function generateMessageId() {
return '' + (Date.now() + Math.floor(Math.random()*10000));
}
function _logToConsole(shortMessage, opts) {
var
consoleString = shortMessage,
additionalFields = [];
if (opts.full_message) {
consoleString+=" ("+opts.full_message+")\n";
}
Object.keys(opts).forEach(function(key) {
if (key[0]=='_' && key!="_logSequence") {
additionalFields.push(
" " +
key.substr(1,1024) +
": " +
'\033[' + 34 + 'm' +
opts[key] +
'\033[' + 39 + 'm'
);
}
});
if (additionalFields.length>0) {
consoleString+="\n"+additionalFields.join("\n");
}
util.log(consoleString);
}
function sendChunked(graylog2Client, compressedMessage, address) {
var
messageId = generateMessageId(),
sequenceSize = Math.ceil(compressedMessage.length / GLOBAL.graylogChunkSize),
byteOffset = 0,
chunksWritten = 0;
if (sequenceSize > 128) {
util.debug("Graylog oops: log message is larger than 128 chunks, I print to stderr and give up: \n" + compressedMessage.toString());
return;
}
for(var sequence=0; sequence<sequenceSize; sequence++) {
var
chunkBytes = (byteOffset + GLOBAL.graylogChunkSize) < compressedMessage.length ? GLOBAL.graylogChunkSize : (compressedMessage.length - byteOffset),
chunk = new Buffer(chunkBytes + 12);
chunk[0] = 0x1e;
chunk[1] = 0x0f;
chunk.write(messageId, 2, 8, 'ascii');
chunk[10] = sequence;
chunk[11] = sequenceSize;
compressedMessage.copy(chunk, 12, byteOffset, byteOffset+chunkBytes);
byteOffset += chunkBytes;
graylog2Client.send(chunk, 0, chunk.length, GLOBAL.graylogPort, address, function (err, byteCount) {
chunksWritten++;
if (chunksWritten == sequenceSize) {
graylog2Client.close();
}
});
}
}
function sendSingleShot(graylog2Client, compressedMessage, address) {
graylog2Client.send(compressedMessage, 0, compressedMessage.length, GLOBAL.graylogPort, address, function (err, byteCount) {
graylog2Client.close();
});
}
function resolveAndSend(graylog2Client, compressedMessage, dnsName, sendFunc) {
dns.resolve4(GLOBAL.graylogHost, function(dnsErr, addr) {
if (dnsErr) {
util.debug("Graylog oops: DNS Error (" + dnsErr + "), I print to stderr and give up: \n");
return;
}
sendFunc(graylog2Client, compressedMessage, addr[0]);
});
}
function log(shortMessage, a, b) {
var opts = {};
if (typeof a == 'string'){
opts = b || {};
opts.full_message=a;
} else if (typeof a == 'object') {
opts = a || {};
}
opts.version=GLOBAL.gelfVersion;
opts.timestamp = opts.timestamp || new Date().getTime()/1000 >> 0;
opts.host = opts.host || GLOBAL.graylogHostname;
opts.level = opts.level !== undefined ? opts.level : GLOBAL.LOG_INFO;
opts.facility = opts.facility || GLOBAL.graylogFacility;
// Add global additional fields to the message
var additionalFields = GLOBAL.graylogAdditionalFields;
Object.keys(additionalFields).forEach(function(prop) {
// Don't overwrite log level additional fields
if (typeof opts[prop] === 'undefined') {
opts[prop] = additionalFields[prop];
}
});
if (opts.stack) {
retrieveFileInfo(opts);
}
if (GLOBAL.graylogSequence) {
opts['_logSequence'] = GLOBAL.graylogSequence++;
}
opts.short_message = shortMessage;
if (GLOBAL.graylogToConsole) {
_logToConsole(shortMessage, opts);
}
var
message = new Buffer(JSON.stringify(opts)),
sendFunc = sendSingleShot;
zlib.deflate(message, function (err, compressedMessage) {
if (err) {
return;
}
var graylog2Client = dgram.createSocket("udp4");
if (compressedMessage.length > GLOBAL.graylogChunkSize) {
sendFunc = sendChunked;
}
if (!net.isIPv4(GLOBAL.graylogHost)) {
resolveAndSend(graylog2Client, compressedMessage, GLOBAL.graylogHost, sendFunc);
} else {
sendFunc(graylog2Client, compressedMessage, GLOBAL.graylogHost);
}
});
}
/**
* Retrieves the filename and line number where log() was called
*
* @param {Object} opts The options object that will be altered with 'file' and 'line' properties
*/
function retrieveFileInfo(opts){
var err = new Error("test"),
stack = (err.stack || "").toString().split(/\r?\n/),
match;
for (var i=0, len = stack.length; i<len; i++){
if ((match = stack[i].match(/^\s*at\s[^\(]+\(([^\):]+):(\d+):\d+\)/))){
if (__filename.substr(-match[1].length) == match[1]){
continue;
}
opts.file = match[1];
opts.line = Number(match[2]) || 0;
break;
}
}
}
GLOBAL.log = log;