forked from egorFiNE/node-graylog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraylog.js
95 lines (77 loc) · 2.43 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
var zlib = require('zlib'),
dgram = require('dgram'),
util = require('util');
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;
function _logToConsole(shortMessage, opts) {
var consoleString = shortMessage;
if (opts.full_message) {
consoleString+=" ("+opts.full_message+")\n";
}
var additionalFields = [];
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 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="1.0";
opts.timestamp = opts.timestamp || new Date().getTime()/1000 >> 0;
opts.host = opts.host || GLOBAL.graylogHostname;
opts.level = opts.level || GLOBAL.LOG_INFO;
opts.facility = opts.facility || GLOBAL.graylogFacility;
if (GLOBAL.graylogSequence) {
opts['_logSequence'] = GLOBAL.graylogSequence++;
}
opts.short_message = shortMessage;
if (GLOBAL.graylogToConsole) {
_logToConsole(shortMessage, opts);
}
var message = new Buffer(JSON.stringify(opts));
zlib.deflate(message, function (err, compressedMessage) {
if (err) {
return;
}
if (compressedMessage.length>8192) { // FIXME: support chunked
util.debug("Graylog oops: log message size > 8192, I print to stderr and give up: \n" + message.toString());
return;
}
var graylog2Client = dgram.createSocket("udp4");
graylog2Client.send(compressedMessage, 0, compressedMessage.length, GLOBAL.graylogPort, GLOBAL.graylogHost, function (err, byteCount) {
graylog2Client.close();
});
});
}
GLOBAL.log = log;