forked from cyamato/SyslogPro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
3067 lines (3054 loc) · 105 KB
/
index.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// INDEX.JS
/** Copyright (c) 2018 Craig Yamato */
/**
* @fileoverview The SyslogPro module for sending syslog messages
*
* Syslog formatting classes can be used as input into a Syslog class to be used
* simultaneously to the same Syslog server. The Syslog Class with a configured
* Syslog server target can also be used as the input into each of the
* formatting classes so that they may run independently.
* @author Craig Yamato <[email protected]>
* @copyright (c) 2018 - Craig Yamato
* @version 0.1.0
* @exports Syslog
* @exports LEEF
* @exports CEF
* @module SyslogPro
*/
'use strict';
const moment = require('moment');
const os = require('os');
const dns = require('dns');
let dnsPromises = dns.promises;
const fs = require('fs');
/**
* Format the ANSI foreground color code from a RGB hex code or ANSI color code
* @private
* @param {string} hex - The color hex code in the form of #FFFFFF or Number of
* the ANSI color code (30-37 Standard & 0-255 Extended)
* @returns {Promise} - The formatted ANSI color code
* @throws {Error} - A Format Error
*/
function rgbToAnsi(hex,
extendedColor) {
let colorCode = 0; // Var to hold color code
// Break HEX Code up into RGB
const hexParts = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (hexParts || typeof hex === 'number') {
if (typeof hex === 'number') {
if (extendedColor && hex < 256) {
return hex;
} else if ((hex > 29 && hex < 38) || (hex > 89 && hex < 98)) {
return hex;
} else {
throw new Error('FORMAT ERROR: Color code not in range');
}
} else {
const r = parseInt(hexParts[1], 16);
const g = parseInt(hexParts[2], 16);
const b = parseInt(hexParts[3], 16);
if (extendedColor) {
if (r === g && g === b) {
// Gray Scale Color
if (r < 8) {
colorCode = 16;
} else if (r > 248) {
colorCode = 231;
} else {
colorCode = Math.round(((r - 8) / 247) * 24) + 232;
}
} else {
colorCode = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
}
} else {
colorCode = 30;
const red = r / 255;
const green = g / 255;
const blue = b / 255;
let v = Math.max(red, green, blue) * 100;
v = Math.round(v / 50);
if (v === 1) {
colorCode += ((Math.round(b / 255) << 2)
| (Math.round(g / 255) << 1)
| Math.round(r / 255));
}
if (v === 2) {
colorCode += 60;
}
}
}
return colorCode;
} else {
throw new Error('TYPE ERROR: Not in RGB color hex or color code');
}
}
/**
* A class to work with syslog messages using UDP, TCP, or TLS transport.
* There is support for Syslog message formatting RFC-3164, RFC-5424 including
* Structured Data, IBM LEEF (Log Event Extended Format), and HP CEF (Common
* Event Format).
* Syslog formatting classes can be used as input into a Syslog class to be used
* simultaneously to the same Syslog server. *
* @requires moment
* @version 0.0.0
* @since 0.0.0
*/
class Syslog {
/**
* Construct a new Syslog transport object with user options
* @public
* @version 0.0.0
* @since 0.0.0
* @this Syslog
* @param {object} [options] - Options object
* >>>Transport Configuration
* @param {string} [options.target='localhost'] - The IP Address|FQDN of the
* Syslog Server, this option if set will take presidents over any target
* set in a formatting object
* @param {string} [options.protocol='udp'] - L4 transport protocol
* (udp|tcp|tls), this option if set will take presidents over any
* transport set in a formatting object
* @param {number} [options.port=514] - IP port, this option if set will take
* presidents over any IP Port set in a formatting object
* @param {number} [options.tcpTimeout=10000] - Ignored for all other
* transports, this option if set will take presidents over any timeout
* set in a formatting object
* @param {string[]} [options.tlsServerCerts] - Array of authorized TLS server
* certificates file locations, this option if set will take presidents
* over any certificates set in a formatting object
* @param {string} [options.tlsClientCert] - Client TLS certificate file
* location that this client should use, this option if set will take
* presidents over any certificates set in a formatting object
* @param {string} [options.tlsClientKey] - Client TLS key file
* location that this client should use, this option if set will take
* presidents over any certificates set in a formatting object
* >>>Syslog Format Settings
* @param {string} [options.format='none'] - Valid syslog format options for
* this module are 'none', 'rfc3164', 'rfc5424', 'leef', 'cef'
* @param {RFC3164} [options.rfc5424] - {@link module:SyslogPro~RFC5424|
* RFC5424 related settings}
* @param {RFC5424} [options.rfc5424] - {@link module:SyslogPro~RFC5424|
* RFC5424 related settings}
* @param {LEEF} [options.leef] - {@link module:SyslogPro~LEEF|IBM LEEF
* (Log Event Extended Format) object}
* @param {CEF} [options.cef] - {@link module:SyslogPro~CEF|HP CEF
* (Common Event Format) formatting object}
*/
constructor(options) {
this.constructor__ = true;
if (!options) {
options = {};
}
// Basic transport setup
/** @type {string} */
this.target = options.target || 'localhost';
/** @type {string} */
this.protocol = options.protocol || 'udp';
this.protocol = this.protocol.toLowerCase();
/** @type {number} */
this.port = options.port || 514;
/** @type {number} */
this.tcpTimeout = options.tcpTimeout || 10000;
if ((typeof options.tlsServerCerts === 'object'
&& Array.isArray(options.tlsServerCerts))
|| typeof options.tlsServerCerts === 'string') {
this.addTlsServerCerts(options.tlsServerCerts);
} else {
/** @type {string[]} */
this.tlsServerCerts = [];
}
if (options.tlsClientCert) {
/** @type {string} */
this.tlsClientCert = options.tlsClientCert;
}
if (options.tlsClientKey) {
/** @type {string} */
this.tlsClientKey = options.tlsClientKey;
}
// Syslog Format
if (typeof options.format === 'string') {
/** @type {string} */
this.format = options.format.toLowerCase();
} else {
this.format = options.format || 'none';
}
if (options.rfc3164) {
if (options.rfc3164.constructor__) {
/** @type {RFC3164} */
this.rfc3164 = options.rfc3164;
} else {
this.rfc3164 = new RFC3164(options);
}
}
if (options.rfc5424) {
if (options.rfc5424.constructor__) {
/** @type {RFC5424} */
this.rfc5424 = options.rfc5424;
} else {
this.rfc5424 = new RFC5424(options);
}
}
if (options.leef) {
if (options.leef.constructor__) {
/** @type {LEEF} */
this.leef = options.leef;
} else {
this.leef = new LEEF(options);
}
}
if (options.cef) {
if (options.cef.constructor__) {
/** @type {CEF} */
this.cef = options.cef;
} else {
this.cef = new CEF(options);
}
}
if (this.format === 'rfc3164' && !this.rfc3164) {
this.rfc3164 = new RFC3164();
}
if (this.format === 'rfc5424' && !this.rfc5424) {
this.rfc5424 = new RFC5424();
}
if (this.format === 'leef' && !this.leef) {
this.leef = new LEEF();
}
if (this.format === 'cef' && !this.cef) {
this.cef = new CEF();
}
}
/**
* Add a TLS server certificate which can be used to authenticate the server
* this syslog client is connecting too. This function will validate the
* input as a file location string and add it to an array of certificates
* @private
* @version 0.0.0
* @since 0.0.0
* @param {string|string[]} certs - File location of the certificate(s)
* @returns {boolean} - True
* @throws {Error} - A Type Error
*/
addTlsServerCerts(certs) {
if (typeof certs === 'object' && Array.isArray(certs)) {
/** @private @type {string[]} */
this.tlsServerCerts = certs;
} else if (typeof certs === 'string') {
this.tlsServerCerts = [certs];
} else {
let errMsg =
'TYPE ERROR: Server Cert file locations should be a string';
errMsg += ' or array of strings';
throw new Error(errMsg);
}
return true;
}
/**
* Send the Syslog message over UDP
* @private
* @param {string} msg - The formatted Syslog Message
* @returns {Promise} - The Syslog formatted string sent
* @throws {Error} - Network Error
*/
async udpMessage(msg) {
// Test for target DNS and Address Family (IPv4/6) by looking up the DNS
const dgram = require('dgram');
const dnsOptions = {
verbatim: true,
};
const result = await dnsPromises.lookup(this.target, dnsOptions);
const udpType = result.family === 4 ? 'udp4' : 'udp6';
let client = dgram.createSocket(udpType);
// Turn msg in to a UTF8 buffer
let msgBuffer = Buffer.from(msg, 'utf8');
return new Promise((resolve) => {
client.send(msgBuffer, this.port, this.target, () => {
client.close();
resolve(msg);
});
});
}
/**
* Send the Syslog message over TCP
* @private
* @param {string} msg - The formatted Syslog Message
* @returns {Promise} - The Syslog formatted string sent
* @throws {Error} - Timeout error for TCP and TLS connections
* @throws {Error} - Network Error
*/
async tcpMessage(msg) {
const net = require('net');
const dnsOptions = {
verbatim: true,
};
const result = await dnsPromises.lookup(this.target, dnsOptions);
const tcpOptions = {
host: this.target,
port: this.port,
family: result.family,
};
const client = net.createConnection(tcpOptions, () => {
// Turn msg in to a UTF8 buffer
let msgBuffer = Buffer.from(msg, 'utf8');
client.write(msgBuffer, () => {
client.end();
});
});
client.setTimeout(this.tcpTimeout);
return new Promise((resolve, reject) => {
client.on('end', () => {
resolve(msg);
});
client.on('timeout', () => {
client.end();
reject(new Error('TIMEOUT ERROR: Syslog server TCP timeout'));
});
client.on('error', (error) => {
client.destroy();
reject(error);
});
});
}
/**
* Send the Syslog message over TLS
* @private
* @param {string} msg - The formatted Syslog Message
* @returns {Promise} - The Syslog formatted string sent
* @throws {Error} - Timeout error for TCP and TLS connections
* @throws {Error} - Network Error
*/
async tlsMessage(msg) {
const tls = require('tls');
const tlsOptions = {
host: this.target,
port: this.port,
};
// Load client cert and key if requested
if (typeof this.tlsClientKey === 'string'
&& typeof this.tlsClientCert === 'string') {
tlsOptions.key = fs.readFileSync(this.tlsClientKey);
tlsOptions.cert = fs.readFileSync(this.tlsClientCert);
} else if (typeof this.tlsClientKey !== 'string'
&& typeof this.tlsClientKey !== 'undefined') {
let errMsg = 'TYPE ERROR: TLS Client Key is not a file';
errMsg += 'location string';
throw new Error(errMsg);
} else if (typeof this.tlsClientCert !== 'string'
&& typeof this.tlsClientCert !== 'undefined') {
let errMsg = 'TYPE ERROR: TLS Client Cert is not a file';
errMsg += 'location string';
throw new Error(errMsg);
}
// Load any server certs if provided
let tlsCerts = this.tlsServerCerts.length;
if (tlsCerts > 0) {
let tlsOptionsCerts = [];
for (let certIndex = 0; certIndex < tlsCerts; certIndex++) {
if (typeof this.tlsServerCerts[certIndex] !== 'string') {
let errMsg = 'TYPE ERROR: TLS Server Cert is not a file';
errMsg += 'location string';
throw new Error(errMsg);
}
let cert = fs.readFileSync(this.tlsServerCerts[certIndex]);
tlsOptionsCerts.push(cert);
}
tlsOptions.ca = tlsOptionsCerts;
tlsOptions.rejectUnauthorized = true;
}
const client = tls.connect(tlsOptions, () => {
// Turn msg in to a UTF8 buffer
let msgBuffer = Buffer.from(msg, 'utf8');
client.write(msgBuffer, () => {
client.end();
});
});
client.setTimeout(this.tcpTimeout);
return new Promise((resolve, reject) => {
client.on('end', () => {
resolve(msg);
});
client.on('timeout', () => {
client.end();
reject(new Error('TIMEOUT ERROR: Syslog server TLS timeout'));
});
client.on('error', (error) => {
client.destroy();
reject(error);
});
});
}
/**
* Send the Syslog message to the selected target Syslog server using the
* selected transport.
* @private
* @param {string} msg - The formatted Syslog Message
* @returns {Promise} - The Syslog formatted string sent
* @throws {Error} - Timeout error for TCP and TLS connections
* @throws {Error} - Network Error
*/
async send(msg) {
if (typeof msg !== 'string') {
throw new Error('TYPE ERROR: Syslog message must be a string');
}
this.protocol = this.protocol.toLowerCase();
if (this.protocol === 'udp') {
return this.udpMessage(msg);
} else if (this.protocol === 'tcp') {
return this.tcpMessage(msg);
} else if (this.protocol === 'tls') {
return this.tlsMessage(msg);
} else {
let errorMsg = 'FORMAT ERROR: Protocol not recognized, should be ';
errorMsg += 'udp|tcp|tls';
throw new Error(errorMsg);
}
}
}
/**
* The base class of RFC formartted syslog messages.
*/
class RFC {
/**
* Sets the color to be used for messages at a set priority
* @public
* @param {string} [colors.emergencyColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @param {string} [colors.alertColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @param {string} [colors.criticalColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @param {string} [colors.errorColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @param {string} [colors.warningColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @param {string} [colors.noticeColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @param {string} [colors.informationalColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [colors.debugColor] - A RGB Hex coded color in the form
* of #FFFFFF or as or the ANSI color code number (30-37 Standard & 0-255
* Extended)
* @throws {Error} A standard error object
*/
setColor(colors, extendedColor) {
if (colors.emergencyColor) {
try {
this.emergencyColor = rgbToAnsi(
colors.emergencyColor,
this.extendedColor
);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'emergencyColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.alertColor) {
try {
this.alertColor = rgbToAnsi(colors.alertColor, this.extendedColor);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'alertColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.criticalColor) {
try {
this.criticalColor = rgbToAnsi(
colors.criticalColor,
this.extendedColor
);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'criticalColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.errorColor) {
try {
this.errorColor = rgbToAnsi(colors.errorColor, this.extendedColor);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'errorColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.warningColor) {
try {
this.warningColor = rgbToAnsi(colors.warningColor, this.extendedColor);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'warningColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.noticeColor) {
try {
this.noticeColor = rgbToAnsi(colors.noticeColor, this.extendedColor);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'noticeColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.informationalColor) {
try {
this.informationalColor = rgbToAnsi(
colors.informationalColor,
this.extendedColor
);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'informationalColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
if (colors.debugColor) {
try {
this.debugColor = rgbToAnsi(colors.debugColor, this.extendedColor);
} catch (reason) {
reason.message = 'TYPE ERROR: ';
reason.message += 'debugColor';
reason.message += ' Not in RGB color hex or color code';
throw reason;
}
}
return true;
}
}
/**
* A class to work with RFC3164 formatted syslog messages. The messaging is
* fully configurable and ANSI foreground colors can be added. Both ANSI 8 and
* ANSI 256 color are fully supported.
*
* A Syslog class with a configured
* Syslog server target can also be used as the input into the formatting
* classes so that it may run independently.
*
* The RFC3164 Syslog logging format is meant to be used as a stream of log data
* from a service or application. This class is designed to be used in this
* fashion where new messages are written to the class as needed.
* @requires moment
* @version 0.0.0
* @since 0.0.0
*/
class RFC3164 extends RFC {
/**
* Construct a new RFC3164 formatted Syslog object with user options
* @public
* @this RFC3164
* @param {object} [options] - Options object
* @param {string} [options.applicationName='NodeJSLogger'] - Application
* @param {string} [options.hostname=os.hostname] - The name of this server
* @param {number} [options.facility=23] - Facility code to use sending this
* message
* @param {boolean} [options.color=false] - Apply color coding encoding tag
* with syslog message text
* @param {boolean} [options.extendedColor=false] - Use the extended ANSI
* color set encoding tag with syslog message text
* @param {object} [options.colors] - User defended colors for
* severities
* @param {string} [options.colors.emergencyColor] - A RGB Hex coded color in
* the form of #FFFFFF or as or the ANSI color code number (30-37 Standard
* & 0-255 Extended)
* @param {string} [options.colors.alertColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [options.colors.criticalColor] - A RGB Hex coded color in
* the form of #FFFFFF or as or the ANSI color code number (30-37 Standard
* & 0-255 Extended)
* @param {string} [options.colors.errorColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [options.colors.warningColor] - A RGB Hex coded color in
* the form of #FFFFFF or as or the ANSI color code number (30-37 Standard
* & 0-255 Extended)
* @param {string} [options.colors.noticeColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [options.colors.informationalColor] - A RGB Hex coded color
* in the form of #FFFFFF or as or the ANSI color code number (30-37
* Standard & 0-255 Extended)
* @param {string} [options.colors.debugColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {Syslog} [options.server=false] - A {@link module:SyslogPro~Syslog|
* Syslog server connection} that should be used to send messages directly
* from this class. @see SyslogPro~Syslog
*/
constructor(options) {
super();
/** @private @type {boolean} */
this.constructor__ = true;
options = options || {};
this.hostname = options.hostname || os.hostname();
if (options.applicationName) {
this.applicationName = options.applicationName;
} else {
this.applicationName = options.applacationName || '';
}
this.facility = options.facility || 23;
if (options.color) {
/** @type {boolean} */
this.color = true;
} else {
this.color = false;
}
if (options.extendedColor) {
/** @type {boolean} */
this.extendedColor = true;
} else {
this.extendedColor = false;
}
if (options.server) {
if (!options.server.constructor__) {
/** @private @type {Syslog} */
this.server = new Syslog(options.server);
} else {
this.server = options.server;
}
}
if (this.extendedColor) {
/** @private @type {number} */
this.emergencyColor = 1; // Red foreground color
/** @private @type {number} */
this.alertColor = 202; // Dark Orange foreground color
/** @private @type {number} */
this.criticalColor = 208; // Orange foreground color
/** @private @type {number} */
this.errorColor = 178; // Light Orange foreground color
/** @private @type {number} */
this.warningColor = 226; // Yellow foreground color
/** @private @type {number} */
this.noticeColor = 117; // Light Blue foreground color
/** @private @type {number} */
this.informationalColor = 45; // Blue foreground color
/** @private @type {number} */
this.debugColor = 27; // Dark Blue foreground color
} else {
this.emergencyColor = 31; // Red foreground color
this.alertColor = 31; // Red foreground color
this.criticalColor = 31; // Red foreground color
this.errorColor = 33; // Yellow foreground color
this.warningColor = 33; // Yellow foreground color
this.noticeColor = 36; // Blue foreground color
this.informationalColor = 36; // Blue foreground color
this.debugColor = 34; // Dark Blue foreground color
}
if (typeof options.colors === 'object') {
this.setColor(options.colors, this.extendedColor);
}
}
/**
* Building a formatted message. Returns a promise with a formatted message
* @public
* @param {string} msg - The Syslog Message
* @param {object} [options] - Options object
* @param {number} [options.severity=7] - An array of structure
* @param {number} [options.colorCode=36] - The ANSI color code to use if
* message coloration is selected
* @returns {Promise} A Syslog formatted string according to the selected RFC
* @throws {Error} A standard error object
*/
buildMessage(msg, options) {
options = options || {};
let severity = typeof options.severity === 'number' ?
options.severity : 6;
if (typeof msg !== 'string' || options.msgSeverity > 7) {
let errMsg = 'FORMAT ERROR: Syslog message must be a string';
errMsg += ' msgSeverity must be a number between 0 and 7';
throw new Error(errMsg);
}
let fmtMsg = ''; // Formatted Syslog message string var
const newLine = '\n';
const newLineRegEx = /(\r|\n|(\r\n))/;
const escapeCode = '\u001B';
const resetColor = '\u001B[0m';
// The PRI is common to both RFC formats
const pri = (this.facility * 8) + severity;
// Remove any newline character
msg = msg.replace(newLineRegEx, '');
// Add requested color
if (this.color) {
options.msgColor = options.msgColor || 36;
let colorCode = '[';
if (this.extendedColor) {
colorCode += '38;5;'; // Extended 256 Colors ANSI Code
}
if (typeof options.msgColor === 'number') {
colorCode += options.msgColor;
colorCode += 'm'; // ANSI Color Closer
} else {
colorCode = '[39m'; // Use terminal's default color
}
msg = escapeCode + colorCode + msg + resetColor;
}
// RegEx to find a leading 0 in the day of a DateTime for RFC3164 RFC3164
// uses BSD timeformat
const rfc3164DateRegEx =
/((A|D|F|J|M|N|O|S)(a|c|e|p|o|u)(b|c|g|l|n|p|r|t|v|y)\s)0(\d\s\d\d:\d\d:\d\d)/;
const timestamp = moment()
.format('MMM DD hh:mm:ss')
.replace(rfc3164DateRegEx, '$1 $5');
// Build message
fmtMsg = '<' + pri + '>';
fmtMsg += timestamp;
fmtMsg += ' ' + this.hostname;
fmtMsg += ' ' + this.applicationName;
fmtMsg += ' ' + msg;
fmtMsg += newLine;
return fmtMsg;
}
/**
* send a RFC5424 formatted message. Returns a promise with the formatted
* message that was sent. If no server connection was defined when the
* class was created a default Syslog connector will be used.
* @see SyslogPro~Syslog
* @public
* @param {string} msg - The unformatted Syslog message to send
* @param {object} [options] - Options object
* @param {number} [options.severity=7] - An array of structure
* @param {number} [options.colorCode=36] - The ANSI color code to use if
* @returns {Promise} A Syslog formatted string according to the selected RFC
* @throws {Error} A standard error object
*/
async send(msg, options) {
if (!this.server) {
this.server = new Syslog();
}
const result = this.buildMessage(msg, options);
return this.server.send(result);
}
/**
* Send a syslog message with a security level of 0 (Emergency)
* @public
* @param {string} msg - The emergency message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
emergency(msg) {
return this.send(msg, {
severity: 0,
colorCode: this.emergencyColor,
});
}
/**
* Send a syslog message with a security level of 0 (Emergency)
* @public
* @param {string} msg - The emergency message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
emer(msg) {
return this.emergency(msg);
}
/**
* Send a syslog message with a severity level of 1 (Alert)
* @public
* @param {string} msg - The alert message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
alert(msg) {
return this.send(msg, {
severity: 1,
colorCode: this.alertColor,
});
}
/**
* Send a syslog message with a severity level of 2 (Critical)
* @public
* @param {string} msg - The critical message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
critical(msg) {
return this.send(msg, {
severity: 2,
colorCode: this.criticalColor,
});
}
/**
* Send a syslog message with a severity level of 2 (Critical)
* @public
* @param {string} msg - The critical message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
crit(msg) {
return this.critical(msg);
}
/**
* Send a syslog message with a severity level of 3 (Error)
* @public
* @param {string} msg - The error message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
error(msg) {
return this.send(msg, {
severity: 3,
colorCode: this.errorColor,
});
}
/**
* Send a syslog message with a severity level of 3 (Error)
* @public
* @param {string} msg - The error message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
err(msg) {
return this.error(msg);
}
/**
* Send a syslog message with a severity level of 4 (Warning)
* @public
* @param {string} msg - The warning message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
warning(msg) {
return this.send(msg, {
severity: 4,
colorCode: this.warningColor,
});
}
/**
* Send a syslog message with a severity level of 4 (Warning)
* @public
* @param {string} msg - The warning message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
warn(msg) {
return this.warning(msg);
}
/**
* Send a syslog message with a severity level of 5 (Notice)
* @public
* @param {string} msg - The notice message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
notice(msg) {
return this.send(msg, {
severity: 5,
colorCode: this.noticeColor,
});
}
/**
* Send a syslog message with a severity level of 5 (Notice)
* @public
* @param {string} msg - The notice message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
note(msg) {
return this.notice(msg);
}
/**
* Send a syslog message with a severity level of 6 (Informational)
* @public
* @param {string} msg - The informational message to send to the Syslog
* server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
informational(msg) {
return this.send(msg, {
severity: 6,
colorCode: this.informationalColor,
});
}
/**
* Send a syslog message with a severity level of 6 (Informational)
* @public
* @param {string} msg - The informational message to send to the Syslog
* server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
info(msg) {
return this.informational(msg);
}
/**
* Send a syslog message with a severity level of 6 (Informational)
* @public
* @param {string} msg - The informational message to send to the Syslog
* server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
log(msg) {
return this.informational(msg);
}
/**
* Send a syslog message with a severity level of 7 (Debug)
* @public
* @param {string} msg - The debug message to send to the Syslog server
* @returns {Promise} - The formatted syslog message sent to the Syslog server
* @throws {Error} - Any bubbled-up error
*/
debug(msg) {
return this.send(msg, {
severity: 7,
colorCode: this.debugColor,
});
}
}
/**
* A class to work with RFC5424 formatted syslog messages. The messaging is
* fully configurable and ANSI foreground * colors can be added. Both ANSI 8
* and ANSI 256 color are fully supported.
*
* A Syslog class with a configured
* Syslog server target can also be used as the input into the formatting
* classes so that it may run independently.
*
* The RFC5424 Syslog logging format is meant to be used as a stream of log data
* from a service or application. This class is designed to be used in this
* fashion where new messages are written to the class as needed.
* @requires moment
* @version 0.0.0
* @since 0.0.0
*/
class RFC5424 extends RFC {
/**
* Construct a new RFC5424 formatted Syslog object with user options
* @public
* @this RFC5424
* @param {object} [options] - Options object
* @param {string} [options.applicationName='NodeJSLogger'] - Application
* @param {string} [options.hostname=os.hostname] - The name of this server
* @param {boolean} [options.timestamp=false] - Included a Timestamp
* @param {boolean} [options.timestampUTC=false] - RFC standard is for
* local time
* @param {boolean} [options.timestampMS=false] - Timestamp with ms
* resolution
* @param {boolean} [options.timestampTZ=true] - Should the timestamp
* included time zone
* @param {boolean} [options.includeStructuredData=false] - Included
* any provided structured data
* @param {boolean} [options.utf8BOM=true] - Included the UTF8
* @param {boolean} [options.color=false] - Included the UTF8
* @param {boolean} [options.extendedColor=false] - Included the UTF8
* encoding tag with syslog message text
* @param {object} [options.colors] - User defended colors for
* severities
* @param {string} [options.colors.emergencyColor] - A RGB Hex coded color in
* the form of #FFFFFF or as or the ANSI color code number (30-37 Standard
* & 0-255 Extended)
* @param {string} [options.colors.alertColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [options.colors.criticalColor] - A RGB Hex coded color in
* the form of #FFFFFF or as or the ANSI color code number (30-37 Standard
* & 0-255 Extended)
* @param {string} [options.colors.errorColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [options.colors.warningColor] - A RGB Hex coded color in
* the form of #FFFFFF or as or the ANSI color code number (30-37 Standard
* & 0-255 Extended)
* @param {string} [options.colors.noticeColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {string} [options.colors.informationalColor] - A RGB Hex coded color
* in the form of #FFFFFF or as or the ANSI color code number (30-37
* Standard & 0-255 Extended)
* @param {string} [options.colors.debugColor] - A RGB Hex coded color in the
* form of #FFFFFF or as or the ANSI color code number (30-37 Standard &
* 0-255 Extended)
* @param {Syslog} [options.server=false] - A {@link module:SyslogPro~Syslog|
* Syslog server connection} that should be used to send messages directly
* from this class. @see SyslogPro~Syslog
*/
constructor(options) {
super();
/** @private @type {boolean} */
this.constructor__ = true;
options = options || {};
this.hostname = options.hostname || os.hostname();
if (options.applicationName) {
this.applicationName = options.applicationName;
} else {
this.applicationName = options.applacationName || '';
}