-
Notifications
You must be signed in to change notification settings - Fork 515
/
bunyan
executable file
·1675 lines (1527 loc) · 53.7 KB
/
bunyan
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
#!/usr/bin/env node
/**
* Copyright 2020 Trent Mick
* Copyright 2020 Joyent Inc.
*
* bunyan -- filter and pretty-print Bunyan log files (line-delimited JSON)
*
* See <https://github.com/trentm/node-bunyan>.
*
* -*- mode: js -*-
* vim: expandtab:ts=4:sw=4
*/
var p = console.log;
var util = require('util');
var pathlib = require('path');
var vm = require('vm');
var http = require('http');
var fs = require('fs');
var warn = console.warn;
var child_process = require('child_process'),
spawn = child_process.spawn,
exec = child_process.exec,
execFile = child_process.execFile;
var assert = require('assert');
var exeunt = require('exeunt');
try {
var moment = require('moment');
} catch (e) {
moment = null;
}
//---- globals and constants
var nodeVer = process.versions.node.split('.').map(Number);
var nodeSpawnSupportsStdio = (nodeVer[0] > 0 || nodeVer[1] >= 8);
// Internal debug logging via `console.warn`.
var _selfTrace = function selfTraceNoop() {};
if (process.env.BUNYAN_SELF_TRACE === '1') {
_selfTrace = function selfTrace() {
process.stderr.write('[bunyan self-trace] ');
console.warn.apply(null, arguments);
}
}
// Output modes.
var OM_LONG = 1;
var OM_JSON = 2;
var OM_INSPECT = 3;
var OM_SIMPLE = 4;
var OM_SHORT = 5;
var OM_BUNYAN = 6;
var OM_FROM_NAME = {
'long': OM_LONG,
'paul': OM_LONG, /* backward compat */
'json': OM_JSON,
'inspect': OM_INSPECT,
'simple': OM_SIMPLE,
'short': OM_SHORT,
'bunyan': OM_BUNYAN
};
// Levels
var TRACE = 10;
var DEBUG = 20;
var INFO = 30;
var WARN = 40;
var ERROR = 50;
var FATAL = 60;
var levelFromName = {
'trace': TRACE,
'debug': DEBUG,
'info': INFO,
'warn': WARN,
'error': ERROR,
'fatal': FATAL
};
var nameFromLevel = {};
var upperNameFromLevel = {};
var upperPaddedNameFromLevel = {};
Object.keys(levelFromName).forEach(function (name) {
var lvl = levelFromName[name];
nameFromLevel[lvl] = name;
upperNameFromLevel[lvl] = name.toUpperCase();
upperPaddedNameFromLevel[lvl] = (
name.length === 4 ? ' ' : '') + name.toUpperCase();
});
// Display time formats.
var TIME_UTC = 1; // the default, bunyan's native format
var TIME_LOCAL = 2;
// Timezone formats: output format -> momentjs format string
var TIMEZONE_UTC_FORMATS = {
long: '[[]YYYY-MM-DD[T]HH:mm:ss.SSS[Z][]]',
short: 'HH:mm:ss.SSS[Z]'
};
var TIMEZONE_LOCAL_FORMATS = {
long: '[[]YYYY-MM-DD[T]HH:mm:ss.SSSZ[]]',
short: 'HH:mm:ss.SSS'
};
// Boolean set to true when we are in the process of exiting. We don't always
// hard-exit (e.g. when staying alive while the pager completes).
var exiting = false;
// The current raw input line being processed. Used for `uncaughtException`.
var currLine = null;
// Child dtrace process, if any. Used for signal-handling.
var child = null;
// Whether ANSI codes are being used. Used for signal-handling.
var usingAnsiCodes = false;
// Used to tell the 'uncaughtException' handler that '-c CODE' is being used.
var gUsingConditionOpts = false;
// Pager child process, and output stream to which to write.
var pager = null;
var stdout = process.stdout;
//---- support functions
var _version = null;
function getVersion() {
if (_version === null) {
_version = require('../package.json').version;
}
return _version;
}
var format = util.format;
if (!format) {
/* BEGIN JSSTYLED */
// If not node 0.6, then use its `util.format`:
// <https://github.com/joyent/node/blob/master/lib/util.js#L22>:
var inspect = util.inspect;
var formatRegExp = /%[sdj%]/g;
format = function format(f) {
if (typeof f !== 'string') {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function (x) {
if (i >= len)
return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j': return JSON.stringify(args[i++]);
case '%%': return '%';
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
/* END JSSTYLED */
}
function indent(s) {
return ' ' + s.split(/\r?\n/).join('\n ');
}
function objCopy(obj) {
if (obj === null) {
return null;
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
var copy = {};
Object.keys(obj).forEach(function (k) {
copy[k] = obj[k];
});
return copy;
}
}
function printHelp() {
/* BEGIN JSSTYLED */
p('Usage:');
p(' bunyan [OPTIONS] [FILE ...]');
p(' ... | bunyan [OPTIONS]');
p(' bunyan [OPTIONS] -p PID');
p('');
p('Filter and pretty-print Bunyan log file content.');
p('');
p('General options:');
p(' -h, --help print this help info and exit');
p(' --version print version of this command and exit');
p('');
p('Runtime log snooping (via DTrace, only on supported platforms):');
p(' -p PID Process bunyan:log-* probes from the process');
p(' with the given PID. Can be used multiple times,');
p(' or specify all processes with "*", or a set of');
p(' processes whose command & args match a pattern');
p(' with "-p NAME".');
p('');
p('Filtering options:');
p(' -l, --level LEVEL');
p(' Only show messages at or above the specified level.');
p(' You can specify level *names* or the internal numeric');
p(' values.');
p(' -c, --condition CONDITION');
p(' Run each log message through the condition and');
p(' only show those that return truish. E.g.:');
p(' -c \'this.pid == 123\'');
p(' -c \'this.level == DEBUG\'');
p(' -c \'this.msg.indexOf("boom") != -1\'');
p(' "CONDITION" must be legal JS code. `this` holds');
p(' the log record. The TRACE, DEBUG, ... FATAL values');
p(' are defined to help with comparing `this.level`.');
p(' --strict Suppress all but legal Bunyan JSON log lines. By default');
p(' non-JSON, and non-Bunyan lines are passed through.');
p('');
p('Output options:');
p(' --pager Pipe output into `less` (or $PAGER if set), if');
p(' stdout is a TTY. This overrides $BUNYAN_NO_PAGER.');
p(' Note: Paging is only supported on node >=0.8.');
p(' --no-pager Do not pipe output into a pager.');
p(' --color Colorize output. Defaults to try if output');
p(' stream is a TTY.');
p(' --no-color Force no coloring (e.g. terminal doesn\'t support it)');
p(' -o, --output MODE');
p(' Specify an output mode/format. One of');
p(' long: (the default) pretty');
p(' json: JSON output, 2-space indent');
p(' json-N: JSON output, N-space indent, e.g. "json-4"');
p(' bunyan: 0 indented JSON, bunyan\'s native format');
p(' inspect: node.js `util.inspect` output');
p(' short: like "long", but more concise');
p(' simple: level, followed by "-" and then the message');
p(' -j shortcut for `-o json`');
p(' -0 shortcut for `-o bunyan`');
p(' -L, --time local');
p(' Display time field in local time, rather than UTC.');
p('');
p('Environment Variables:');
p(' BUNYAN_NO_COLOR Set to a non-empty value to force no output ');
p(' coloring. See "--no-color".');
p(' BUNYAN_NO_PAGER Disable piping output to a pager. ');
p(' See "--no-pager".');
p('');
p('See <https://github.com/trentm/node-bunyan> for more complete docs.');
p('Please report bugs to <https://github.com/trentm/node-bunyan/issues>.');
/* END JSSTYLED */
}
/*
* If the user specifies multiple input sources, we want to print out records
* from all sources in a single, chronologically ordered stream. To do this
* efficiently, we first assume that all records within each source are ordered
* already, so we need only keep track of the next record in each source and
* the time of the last record emitted. To avoid excess memory usage, we
* pause() streams that are ahead of others.
*
* 'streams' is an object indexed by source name (file name) which specifies:
*
* stream Actual stream object, so that we can pause and resume it.
*
* records Array of log records we've read, but not yet emitted. Each
* record includes 'line' (the raw line), 'rec' (the JSON
* record), and 'time' (the parsed time value).
*
* done Whether the stream has any more records to emit.
*/
var streams = {};
function gotRecord(file, line, rec, opts, stylize)
{
var time = new Date(rec.time);
streams[file]['records'].push({ line: line, rec: rec, time: time });
emitNextRecord(opts, stylize);
}
function filterRecord(rec, opts)
{
if (opts.level && rec.level < opts.level) {
return false;
}
if (opts.condFuncs) {
var recCopy = objCopy(rec);
for (var i = 0; i < opts.condFuncs.length; i++) {
var pass = opts.condFuncs[i].call(recCopy);
if (!pass)
return false;
}
} else if (opts.condVm) {
for (var i = 0; i < opts.condVm.length; i++) {
var pass = opts.condVm[i].runInNewContext(rec);
if (!pass)
return false;
}
}
return true;
}
function emitNextRecord(opts, stylize)
{
var ofile, ready, minfile, rec;
for (;;) {
/*
* Take a first pass through the input streams to see if we have a
* record from all of them. If not, we'll pause any streams for
* which we do already have a record (to avoid consuming excess
* memory) and then wait until we have records from the others
* before emitting the next record.
*
* As part of the same pass, we look for the earliest record
* we have not yet emitted.
*/
minfile = undefined;
ready = true;
for (ofile in streams) {
if (streams[ofile].stream === null ||
(!streams[ofile].done && streams[ofile].records.length === 0)) {
ready = false;
break;
}
if (streams[ofile].records.length > 0 &&
(minfile === undefined ||
streams[minfile].records[0].time >
streams[ofile].records[0].time)) {
minfile = ofile;
}
}
if (!ready || minfile === undefined) {
for (ofile in streams) {
if (!streams[ofile].stream || streams[ofile].done)
continue;
if (streams[ofile].records.length > 0) {
if (!streams[ofile].paused) {
streams[ofile].paused = true;
streams[ofile].stream.pause();
}
} else if (streams[ofile].paused) {
streams[ofile].paused = false;
streams[ofile].stream.resume();
}
}
return;
}
/*
* Emit the next record for 'minfile', and invoke ourselves again to
* make sure we emit as many records as we can right now.
*/
rec = streams[minfile].records.shift();
emitRecord(rec.rec, rec.line, opts, stylize);
}
}
/**
* Return a function for the given JS code that returns.
*
* If no 'return' in the given javascript snippet, then assume we are a single
* statement and wrap in 'return (...)'. This is for convenience for short
* '-c ...' snippets.
*/
function funcWithReturnFromSnippet(js) {
// auto-"return"
if (js.indexOf('return') === -1) {
if (js.substring(js.length - 1) === ';') {
js = js.substring(0, js.length - 1);
}
js = 'return (' + js + ')';
}
// Expose level definitions to condition func context
var varDefs = [];
Object.keys(upperNameFromLevel).forEach(function (lvl) {
varDefs.push(format('var %s = %d;',
upperNameFromLevel[lvl], lvl));
});
varDefs = varDefs.join('\n') + '\n';
return (new Function(varDefs + js));
}
/**
* Parse the command-line options and arguments into an object.
*
* {
* 'args': [...] // arguments
* 'help': true, // true if '-h' option given
* // etc.
* }
*
* @return {Object} The parsed options. `.args` is the argument list.
* @throws {Error} If there is an error parsing argv.
*/
function parseArgv(argv) {
var parsed = {
args: [],
help: false,
color: null,
paginate: null,
outputMode: OM_LONG,
jsonIndent: 2,
level: null,
strict: false,
pids: null,
pidsType: null,
timeFormat: TIME_UTC // one of the TIME_ constants
};
// Turn '-iH' into '-i -H', except for argument-accepting options.
var args = argv.slice(2); // drop ['node', 'scriptname']
var newArgs = [];
var optTakesArg = {'d': true, 'o': true, 'c': true, 'l': true, 'p': true};
for (var i = 0; i < args.length; i++) {
if (args[i].charAt(0) === '-' && args[i].charAt(1) !== '-' &&
args[i].length > 2)
{
var splitOpts = args[i].slice(1).split('');
for (var j = 0; j < splitOpts.length; j++) {
newArgs.push('-' + splitOpts[j]);
if (optTakesArg[splitOpts[j]]) {
var optArg = splitOpts.slice(j+1).join('');
if (optArg.length) {
newArgs.push(optArg);
}
break;
}
}
} else {
newArgs.push(args[i]);
}
}
args = newArgs;
// Expose level definitions to condition vm context
var condDefines = [];
Object.keys(upperNameFromLevel).forEach(function (lvl) {
condDefines.push(
format('Object.prototype.%s = %s;', upperNameFromLevel[lvl], lvl));
});
condDefines = condDefines.join('\n') + '\n';
var endOfOptions = false;
while (args.length > 0) {
var arg = args.shift();
switch (arg) {
case '--':
endOfOptions = true;
break;
case '-h': // display help and exit
case '--help':
parsed.help = true;
break;
case '--version':
parsed.version = true;
break;
case '--strict':
parsed.strict = true;
break;
case '--color':
parsed.color = true;
break;
case '--no-color':
parsed.color = false;
break;
case '--pager':
parsed.paginate = true;
break;
case '--no-pager':
parsed.paginate = false;
break;
case '-o':
case '--output':
var name = args.shift();
var idx = name.lastIndexOf('-');
if (idx !== -1) {
var indentation = Number(name.slice(idx+1));
if (! isNaN(indentation)) {
parsed.jsonIndent = indentation;
name = name.slice(0, idx);
}
}
parsed.outputMode = OM_FROM_NAME[name];
if (parsed.outputMode === undefined) {
throw new Error('unknown output mode: "'+name+'"');
}
break;
case '-j': // output with JSON.stringify
parsed.outputMode = OM_JSON;
break;
case '-0':
parsed.outputMode = OM_BUNYAN;
break;
case '-L':
parsed.timeFormat = TIME_LOCAL;
if (!moment) {
throw new Error(
'could not find moment package required for "-L"');
}
break;
case '--time':
var timeArg = args.shift();
switch (timeArg) {
case 'utc':
parsed.timeFormat = TIME_UTC;
break
case 'local':
parsed.timeFormat = TIME_LOCAL;
if (!moment) {
throw new Error('could not find moment package '
+ 'required for "--time=local"');
}
break
case undefined:
throw new Error('missing argument to "--time"');
default:
throw new Error(format('invalid time format: "%s"',
timeArg));
}
break;
case '-p':
if (!parsed.pids) {
parsed.pids = [];
}
var pidArg = args.shift();
var pid = +(pidArg);
if (!isNaN(pid) || pidArg === '*') {
if (parsed.pidsType && parsed.pidsType !== 'num') {
throw new Error(format('cannot mix PID name and '
+ 'number arguments: "%s"', pidArg));
}
parsed.pidsType = 'num';
if (!parsed.pids) {
parsed.pids = [];
}
parsed.pids.push(isNaN(pid) ? pidArg : pid);
} else {
if (parsed.pidsType && parsed.pidsType !== 'name') {
throw new Error(format('cannot mix PID name and '
+ 'number arguments: "%s"', pidArg));
}
parsed.pidsType = 'name';
parsed.pids = pidArg;
}
break;
case '-l':
case '--level':
var levelArg = args.shift();
var level = +(levelArg);
if (isNaN(level)) {
level = +levelFromName[levelArg.toLowerCase()];
}
if (isNaN(level)) {
throw new Error('unknown level value: "'+levelArg+'"');
}
parsed.level = level;
break;
case '-c':
case '--condition':
gUsingConditionOpts = true;
var condition = args.shift();
if (Boolean(process.env.BUNYAN_EXEC &&
process.env.BUNYAN_EXEC === 'vm'))
{
parsed.condVm = parsed.condVm || [];
var scriptName = 'bunyan-condition-'+parsed.condVm.length;
var code = condDefines + condition;
var script;
try {
script = vm.createScript(code, scriptName);
} catch (complErr) {
throw new Error(format('illegal CONDITION code: %s\n'
+ ' CONDITION script:\n'
+ '%s\n'
+ ' Error:\n'
+ '%s',
complErr, indent(code), indent(complErr.stack)));
}
// Ensure this is a reasonably safe CONDITION.
try {
script.runInNewContext(minValidRecord);
} catch (condErr) {
throw new Error(format(
/* JSSTYLED */
'CONDITION code cannot safely filter a minimal Bunyan log record\n'
+ ' CONDITION script:\n'
+ '%s\n'
+ ' Minimal Bunyan log record:\n'
+ '%s\n'
+ ' Filter error:\n'
+ '%s',
indent(code),
indent(JSON.stringify(minValidRecord, null, 2)),
indent(condErr.stack)
));
}
parsed.condVm.push(script);
} else {
parsed.condFuncs = parsed.condFuncs || [];
parsed.condFuncs.push(funcWithReturnFromSnippet(condition));
}
break;
default: // arguments
if (!endOfOptions && arg.length > 0 && arg[0] === '-') {
throw new Error('unknown option "'+arg+'"');
}
parsed.args.push(arg);
break;
}
}
//TODO: '--' handling and error on a first arg that looks like an option.
return parsed;
}
function isInteger(s) {
return (s.search(/^-?[0-9]+$/) == 0);
}
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
// Suggested colors (some are unreadable in common cases):
// - Good: cyan, yellow (limited use), bold, green, magenta, red
// - Bad: blue (not visible on cmd.exe), grey (same color as background on
// Solarized Dark theme from <https://github.com/altercation/solarized>, see
// issue #160)
var colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
function stylizeWithColor(str, color) {
if (!str)
return '';
var codes = colors[color];
if (codes) {
return '\033[' + codes[0] + 'm' + str +
'\033[' + codes[1] + 'm';
} else {
return str;
}
}
function stylizeWithoutColor(str, color) {
return str;
}
/**
* Is this a valid Bunyan log record.
*/
function isValidRecord(rec) {
if (rec.v == null ||
rec.level == null ||
rec.name == null ||
rec.hostname == null ||
rec.pid == null ||
rec.time == null ||
rec.msg == null) {
// Not valid Bunyan log.
return false;
} else {
return true;
}
}
var minValidRecord = {
v: 0, //TODO: get this from bunyan.LOG_VERSION
level: INFO,
name: 'name',
hostname: 'hostname',
pid: 123,
time: Date.now(),
msg: 'msg'
};
/**
* Parses the given log line and either emits it right away (for invalid
* records) or enqueues it for emitting later when it's the next line to show.
*/
function handleLogLine(file, line, opts, stylize) {
if (exiting) {
_selfTrace('warn: handleLogLine called while exiting');
return;
}
currLine = line; // intentionally global
// Emit non-JSON lines immediately.
var rec;
if (!line) {
if (!opts.strict) emit(line + '\n');
return;
} else if (line[0] !== '{') {
if (!opts.strict) emit(line + '\n'); // not JSON
return;
} else {
try {
rec = JSON.parse(line);
} catch (e) {
if (!opts.strict) emit(line + '\n');
return;
}
}
if (!isValidRecord(rec)) {
if (!opts.strict) emit(line + '\n');
return;
}
if (!filterRecord(rec, opts))
return;
if (file === null)
return emitRecord(rec, line, opts, stylize);
return gotRecord(file, line, rec, opts, stylize);
}
/**
* Print out a single result, considering input options.
*/
function emitRecord(rec, line, opts, stylize) {
var short = false;
switch (opts.outputMode) {
case OM_SHORT:
short = true;
/* jsl:fall-thru */
case OM_LONG:
// [time] LEVEL: name[/comp]/pid on hostname (src): msg* (extras...)
// msg*
// --
// long and multi-line extras
// ...
// If 'msg' is single-line, then it goes in the top line.
// If 'req', show the request.
// If 'res', show the response.
// If 'err' and 'err.stack' then show that.
if (!isValidRecord(rec)) {
return emit(line + '\n');
}
delete rec.v;
// Time.
var time;
if (!short && opts.timeFormat === TIME_UTC) {
// Fast default path: We assume the raw `rec.time` is a UTC time
// in ISO 8601 format (per spec).
time = '[' + rec.time + ']';
} else if (!moment && opts.timeFormat === TIME_UTC) {
// Don't require momentjs install, as long as not using TIME_LOCAL.
time = rec.time.substr(11);
} else {
var tzFormat;
var moTime = moment(rec.time);
switch (opts.timeFormat) {
case TIME_UTC:
tzFormat = TIMEZONE_UTC_FORMATS[short ? 'short' : 'long'];
moTime.utc();
break;
case TIME_LOCAL:
tzFormat = TIMEZONE_LOCAL_FORMATS[short ? 'short' : 'long'];
break;
default:
throw new Error('unexpected timeFormat: ' + opts.timeFormat);
};
time = moTime.format(tzFormat);
}
time = stylize(time, 'none');
delete rec.time;
var nameStr = rec.name;
delete rec.name;
if (rec.component) {
nameStr += '/' + rec.component;
}
delete rec.component;
if (!short)
nameStr += '/' + rec.pid;
delete rec.pid;
var level = (upperPaddedNameFromLevel[rec.level] || 'LVL' + rec.level);
if (opts.color) {
var colorFromLevel = {
10: 'white', // TRACE
20: 'yellow', // DEBUG
30: 'cyan', // INFO
40: 'magenta', // WARN
50: 'red', // ERROR
60: 'inverse', // FATAL
};
level = stylize(level, colorFromLevel[rec.level]);
}
delete rec.level;
var src = '';
if (rec.src && rec.src.file) {
var s = rec.src;
if (s.func) {
src = format(' (%s:%d in %s)', s.file, s.line, s.func);
} else {
src = format(' (%s:%d)', s.file, s.line);
}
src = stylize(src, 'green');
}
delete rec.src;
var hostname = rec.hostname;
delete rec.hostname;
var extras = [];
var details = [];
if (rec.req_id) {
extras.push('req_id=' + rec.req_id);
}
delete rec.req_id;
var onelineMsg;
if (rec.msg.indexOf('\n') !== -1) {
onelineMsg = '';
details.push(indent(stylize(rec.msg, 'cyan')));
} else {
onelineMsg = ' ' + stylize(rec.msg, 'cyan');
}
delete rec.msg;
if (rec.req && typeof (rec.req) === 'object') {
var req = rec.req;
delete rec.req;
var headers = req.headers;
if (!headers) {
headers = '';
} else if (typeof (headers) === 'string') {
headers = '\n' + headers;
} else if (typeof (headers) === 'object') {
headers = '\n' + Object.keys(headers).map(function (h) {
return h + ': ' + headers[h];
}).join('\n');
}
var s = format('%s %s HTTP/%s%s', req.method,
req.url,
req.httpVersion || '1.1',
headers
);
delete req.url;
delete req.method;
delete req.httpVersion;
delete req.headers;
if (req.body) {
s += '\n\n' + (typeof (req.body) === 'object'
? JSON.stringify(req.body, null, 2) : req.body);
delete req.body;
}
if (req.trailers && Object.keys(req.trailers) > 0) {
s += '\n' + Object.keys(req.trailers).map(function (t) {
return t + ': ' + req.trailers[t];
}).join('\n');
}
delete req.trailers;
details.push(indent(s));
// E.g. for extra 'foo' field on 'req', add 'req.foo' at
// top-level. This *does* have the potential to stomp on a
// literal 'req.foo' key.
Object.keys(req).forEach(function (k) {
rec['req.' + k] = req[k];
})
}
if (rec.client_req && typeof (rec.client_req) === 'object') {
var client_req = rec.client_req;
delete rec.client_req;
var headers = client_req.headers;
delete client_req.headers;
var s = format('%s %s HTTP/%s%s',
client_req.method,
client_req.url,
client_req.httpVersion || '1.1',
(headers ?
'\n' + Object.keys(headers).map(
function (h) {
return h + ': ' + headers[h];
}).join('\n') :
''));
delete client_req.method;
delete client_req.url;
delete client_req.httpVersion;
if (client_req.body) {
s += '\n\n' + (typeof (client_req.body) === 'object' ?
JSON.stringify(client_req.body, null, 2) :
client_req.body);
delete client_req.body;
}
// E.g. for extra 'foo' field on 'client_req', add
// 'client_req.foo' at top-level. This *does* have the potential
// to stomp on a literal 'client_req.foo' key.
Object.keys(client_req).forEach(function (k) {
rec['client_req.' + k] = client_req[k];
});
details.push(indent(s));
}
function _res(res) {
var s = '';
/*
* Handle `res.header` or `res.headers` as either a string or
* an object of header key/value pairs. Prefer `res.header` if set,
* because that's what Bunyan's own `res` serializer specifies,
* because that's the value in Node.js's core HTTP server response
* implementation that has all the implicit headers.
*
* Note: `res.header` (string) typically includes the 'HTTP/1.1 ...'
* status line.
*/
var headerTypes = {string: true, object: true};
var headers;
var headersStr = '';
var headersHaveStatusLine = false;
if (res.header && headerTypes[typeof (res.header)]) {
headers = res.header;
delete res.header;
} else if (res.headers && headerTypes[typeof (res.headers)]) {
headers = res.headers;
delete res.headers;
}
if (headers === undefined) {
/* pass through */
} else if (typeof (headers) === 'string') {
headersStr = headers.trimRight(); // Trim the CRLF.
if (headersStr.slice(0, 5) === 'HTTP/') {
headersHaveStatusLine = true;
}
} else {
headersStr += Object.keys(headers).map(
function (h) { return h + ': ' + headers[h]; }).join('\n');
}
/*
* Add a 'HTTP/1.1 ...' status line if the headers didn't already
* include it.
*/
if (!headersHaveStatusLine && res.statusCode !== undefined) {
s += format('HTTP/1.1 %s %s\n', res.statusCode,
http.STATUS_CODES[res.statusCode]);
}
delete res.statusCode;