forked from philmander/browser-bunyan
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
7446 lines (6392 loc) · 210 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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bunyan = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (Buffer,process){
/**
* Copyright (c) 2017 Trent Mick.
* Copyright (c) 2017 Joyent Inc.
*
* The bunyan logging library for node.js.
*
* -*- mode: js -*-
* vim: expandtab:ts=4:sw=4
*/
/*
* Bunyan log format version. This becomes the 'v' field on all log records.
* This will be incremented if there is any backward incompatible change to
* the log record format. Details will be in 'CHANGES.md' (the change log).
*/
var LOG_VERSION = 0;
var xxx = function xxx(s) { // internal dev/debug logging
var args = ['XX' + 'X: '+s].concat(
Array.prototype.slice.call(arguments, 1));
console.error.apply(this, args);
};
var xxx = function xxx() {}; // comment out to turn on debug logging
/*
* Runtime environment notes:
*
* Bunyan is intended to run in a number of runtime environments. Here are
* some notes on differences for those envs and how the code copes.
*
* - node.js: The primary target environment.
* - NW.js: http://nwjs.io/ An *app* environment that feels like both a
* node env -- it has node-like globals (`process`, `global`) and
* browser-like globals (`window`, `navigator`). My *understanding* is that
* bunyan can operate as if this is vanilla node.js.
* - browser: Failing the above, we sniff using the `window` global
* <https://developer.mozilla.org/en-US/docs/Web/API/Window/window>.
* - browserify: http://browserify.org/ A browser-targetting bundler of
* node.js deps. The runtime is a browser env, so can't use fs access,
* etc. Browserify's build looks for `require(<single-string>)` imports
* to bundle. For some imports it won't be able to handle, we "hide"
* from browserify with `require('frobshizzle' + '')`.
* - Other? Please open issues if things are broken.
*/
var runtimeEnv;
if (typeof (process) !== 'undefined' && process.versions) {
if (process.versions.nw) {
runtimeEnv = 'nw';
} else if (process.versions.node) {
runtimeEnv = 'node';
}
}
if (!runtimeEnv && typeof (window) !== 'undefined' &&
window.window === window) {
runtimeEnv = 'browser';
}
if (!runtimeEnv) {
throw new Error('unknown runtime environment');
}
var os, fs, dtrace;
if (runtimeEnv === 'browser') {
os = {
hostname: function () {
return window.location.host;
}
};
fs = {};
dtrace = null;
} else {
os = require('os');
fs = require('fs');
try {
dtrace = require('dtrace-provider' + '');
} catch (e) {
dtrace = null;
}
}
var util = require('util');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var stream = require('stream');
try {
var safeJsonStringify = require('safe-json-stringify');
} catch (e) {
safeJsonStringify = null;
}
if (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) {
safeJsonStringify = null;
}
// The 'mv' module is required for rotating-file stream support.
try {
var mv = require('mv' + '');
} catch (e) {
mv = null;
}
try {
var sourceMapSupport = require('source-map-support' + '');
} catch (_) {
sourceMapSupport = null;
}
//---- Internal support stuff
/**
* A shallow copy of an object. Bunyan logging attempts to never cause
* exceptions, so this function attempts to handle non-objects gracefully.
*/
function objCopy(obj) {
if (obj == null) { // null or undefined
return obj;
} else if (Array.isArray(obj)) {
return obj.slice();
} else if (typeof (obj) === 'object') {
var copy = {};
Object.keys(obj).forEach(function (k) {
copy[k] = obj[k];
});
return copy;
} else {
return obj;
}
}
var format = util.format;
if (!format) {
// If 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 fastAndSafeJsonStringify(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;
};
}
/**
* Gather some caller info 3 stack levels up.
* See <http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi>.
*/
function getCaller3Info() {
if (this === undefined) {
// Cannot access caller info in 'strict' mode.
return;
}
var obj = {};
var saveLimit = Error.stackTraceLimit;
var savePrepare = Error.prepareStackTrace;
Error.stackTraceLimit = 3;
Error.prepareStackTrace = function (_, stack) {
var caller = stack[2];
if (sourceMapSupport) {
caller = sourceMapSupport.wrapCallSite(caller);
}
obj.file = caller.getFileName();
obj.line = caller.getLineNumber();
var func = caller.getFunctionName();
if (func)
obj.func = func;
};
Error.captureStackTrace(this, getCaller3Info);
this.stack;
Error.stackTraceLimit = saveLimit;
Error.prepareStackTrace = savePrepare;
return obj;
}
function _indent(s, indent) {
if (!indent) indent = ' ';
var lines = s.split(/\r?\n/g);
return indent + lines.join('\n' + indent);
}
/**
* Warn about an bunyan processing error.
*
* @param msg {String} Message with which to warn.
* @param dedupKey {String} Optional. A short string key for this warning to
* have its warning only printed once.
*/
function _warn(msg, dedupKey) {
assert.ok(msg);
if (dedupKey) {
if (_warned[dedupKey]) {
return;
}
_warned[dedupKey] = true;
}
process.stderr.write(msg + '\n');
}
function _haveWarned(dedupKey) {
return _warned[dedupKey];
}
var _warned = {};
function ConsoleRawStream() {}
ConsoleRawStream.prototype.write = function (rec) {
if (rec.level < INFO) {
console.log(rec);
} else if (rec.level < WARN) {
console.info(rec);
} else if (rec.level < ERROR) {
console.warn(rec);
} else {
console.error(rec);
}
};
//---- 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 = {};
Object.keys(levelFromName).forEach(function (name) {
nameFromLevel[levelFromName[name]] = name;
});
// Dtrace probes.
var dtp = undefined;
var probes = dtrace && {};
/**
* Resolve a level number, name (upper or lowercase) to a level number value.
*
* @param nameOrNum {String|Number} A level name (case-insensitive) or positive
* integer level.
* @api public
*/
function resolveLevel(nameOrNum) {
var level;
var type = typeof (nameOrNum);
if (type === 'string') {
level = levelFromName[nameOrNum.toLowerCase()];
if (!level) {
throw new Error(format('unknown level name: "%s"', nameOrNum));
}
} else if (type !== 'number') {
throw new TypeError(format('cannot resolve level: invalid arg (%s):',
type, nameOrNum));
} else if (nameOrNum < 0 || Math.floor(nameOrNum) !== nameOrNum) {
throw new TypeError(format('level is not a positive integer: %s',
nameOrNum));
} else {
level = nameOrNum;
}
return level;
}
function isWritable(obj) {
if (obj instanceof stream.Writable) {
return true;
}
return typeof (obj.write) === 'function';
}
//---- Logger class
/**
* Create a Logger instance.
*
* @param options {Object} See documentation for full details. At minimum
* this must include a 'name' string key. Configuration keys:
* - `streams`: specify the logger output streams. This is an array of
* objects with these fields:
* - `type`: The stream type. See README.md for full details.
* Often this is implied by the other fields. Examples are
* 'file', 'stream' and "raw".
* - `level`: Defaults to 'info'.
* - `path` or `stream`: The specify the file path or writeable
* stream to which log records are written. E.g.
* `stream: process.stdout`.
* - `closeOnExit` (boolean): Optional. Default is true for a
* 'file' stream when `path` is given, false otherwise.
* See README.md for full details.
* - `level`: set the level for a single output stream (cannot be used
* with `streams`)
* - `stream`: the output stream for a logger with just one, e.g.
* `process.stdout` (cannot be used with `streams`)
* - `serializers`: object mapping log record field names to
* serializing functions. See README.md for details.
* - `src`: Boolean (default false). Set true to enable 'src' automatic
* field with log call source info.
* All other keys are log record fields.
*
* An alternative *internal* call signature is used for creating a child:
* new Logger(<parent logger>, <child options>[, <child opts are simple>]);
*
* @param _childSimple (Boolean) An assertion that the given `_childOptions`
* (a) only add fields (no config) and (b) no serialization handling is
* required for them. IOW, this is a fast path for frequent child
* creation.
*/
function Logger(options, _childOptions, _childSimple) {
xxx('Logger start:', options)
if (!(this instanceof Logger)) {
return new Logger(options, _childOptions);
}
// Input arg validation.
var parent;
if (_childOptions !== undefined) {
parent = options;
options = _childOptions;
if (!(parent instanceof Logger)) {
throw new TypeError(
'invalid Logger creation: do not pass a second arg');
}
}
if (!options) {
throw new TypeError('options (object) is required');
}
if (!parent) {
if (!options.name) {
throw new TypeError('options.name (string) is required');
}
} else {
if (options.name) {
throw new TypeError(
'invalid options.name: child cannot set logger name');
}
}
if (options.stream && options.streams) {
throw new TypeError('cannot mix "streams" and "stream" options');
}
if (options.streams && !Array.isArray(options.streams)) {
throw new TypeError('invalid options.streams: must be an array')
}
if (options.serializers && (typeof (options.serializers) !== 'object' ||
Array.isArray(options.serializers))) {
throw new TypeError('invalid options.serializers: must be an object')
}
EventEmitter.call(this);
// Fast path for simple child creation.
if (parent && _childSimple) {
// `_isSimpleChild` is a signal to stream close handling that this child
// owns none of its streams.
this._isSimpleChild = true;
this._level = parent._level;
this.streams = parent.streams;
this.serializers = parent.serializers;
this.src = parent.src;
var fields = this.fields = {};
var parentFieldNames = Object.keys(parent.fields);
for (var i = 0; i < parentFieldNames.length; i++) {
var name = parentFieldNames[i];
fields[name] = parent.fields[name];
}
var names = Object.keys(options);
for (var i = 0; i < names.length; i++) {
var name = names[i];
fields[name] = options[name];
}
return;
}
// Start values.
var self = this;
if (parent) {
this._level = parent._level;
this.streams = [];
for (var i = 0; i < parent.streams.length; i++) {
var s = objCopy(parent.streams[i]);
s.closeOnExit = false; // Don't own parent stream.
this.streams.push(s);
}
this.serializers = objCopy(parent.serializers);
this.src = parent.src;
this.fields = objCopy(parent.fields);
if (options.level) {
this.level(options.level);
}
} else {
this._level = Number.POSITIVE_INFINITY;
this.streams = [];
this.serializers = null;
this.src = false;
this.fields = {};
}
if (!dtp && dtrace) {
dtp = dtrace.createDTraceProvider('bunyan');
for (var level in levelFromName) {
var probe;
probes[levelFromName[level]] = probe =
dtp.addProbe('log-' + level, 'char *');
// Explicitly add a reference to dtp to prevent it from being GC'd
probe.dtp = dtp;
}
dtp.enable();
}
// Handle *config* options (i.e. options that are not just plain data
// for log records).
if (options.stream) {
self.addStream({
type: 'stream',
stream: options.stream,
closeOnExit: false,
level: options.level
});
} else if (options.streams) {
options.streams.forEach(function (s) {
self.addStream(s, options.level);
});
} else if (parent && options.level) {
this.level(options.level);
} else if (!parent) {
if (runtimeEnv === 'browser') {
/*
* In the browser we'll be emitting to console.log by default.
* Any console.log worth its salt these days can nicely render
* and introspect objects (e.g. the Firefox and Chrome console)
* so let's emit the raw log record. Are there browsers for which
* that breaks things?
*/
self.addStream({
type: 'raw',
stream: new ConsoleRawStream(),
closeOnExit: false,
level: options.level
});
} else {
self.addStream({
type: 'stream',
stream: process.stdout,
closeOnExit: false,
level: options.level
});
}
}
if (options.serializers) {
self.addSerializers(options.serializers);
}
if (options.src) {
this.src = true;
}
xxx('Logger: ', self)
// Fields.
// These are the default fields for log records (minus the attributes
// removed in this constructor). To allow storing raw log records
// (unrendered), `this.fields` must never be mutated. Create a copy for
// any changes.
var fields = objCopy(options);
delete fields.stream;
delete fields.level;
delete fields.streams;
delete fields.serializers;
delete fields.src;
if (this.serializers) {
this._applySerializers(fields);
}
if (!fields.hostname && !self.fields.hostname) {
fields.hostname = os.hostname();
}
if (!fields.pid) {
fields.pid = process.pid;
}
Object.keys(fields).forEach(function (k) {
self.fields[k] = fields[k];
});
}
util.inherits(Logger, EventEmitter);
/**
* Add a stream
*
* @param stream {Object}. Object with these fields:
* - `type`: The stream type. See README.md for full details.
* Often this is implied by the other fields. Examples are
* 'file', 'stream' and "raw".
* - `path` or `stream`: The specify the file path or writeable
* stream to which log records are written. E.g.
* `stream: process.stdout`.
* - `level`: Optional. Falls back to `defaultLevel`.
* - `closeOnExit` (boolean): Optional. Default is true for a
* 'file' stream when `path` is given, false otherwise.
* See README.md for full details.
* @param defaultLevel {Number|String} Optional. A level to use if
* `stream.level` is not set. If neither is given, this defaults to INFO.
*/
Logger.prototype.addStream = function addStream(s, defaultLevel) {
var self = this;
if (defaultLevel === null || defaultLevel === undefined) {
defaultLevel = INFO;
}
s = objCopy(s);
// Implicit 'type' from other args.
if (!s.type) {
if (s.stream) {
s.type = 'stream';
} else if (s.path) {
s.type = 'file'
}
}
s.raw = (s.type === 'raw'); // PERF: Allow for faster check in `_emit`.
if (s.level !== undefined) {
s.level = resolveLevel(s.level);
} else {
s.level = resolveLevel(defaultLevel);
}
if (s.level < self._level) {
self._level = s.level;
}
switch (s.type) {
case 'stream':
assert.ok(isWritable(s.stream),
'"stream" stream is not writable: ' + util.inspect(s.stream));
if (!s.closeOnExit) {
s.closeOnExit = false;
}
break;
case 'file':
if (s.reemitErrorEvents === undefined) {
s.reemitErrorEvents = true;
}
if (!s.stream) {
s.stream = fs.createWriteStream(s.path,
{flags: 'a', encoding: 'utf8'});
if (!s.closeOnExit) {
s.closeOnExit = true;
}
} else {
if (!s.closeOnExit) {
s.closeOnExit = false;
}
}
break;
case 'rotating-file':
assert.ok(!s.stream,
'"rotating-file" stream should not give a "stream"');
assert.ok(s.path);
assert.ok(mv, '"rotating-file" stream type is not supported: '
+ 'missing "mv" module');
s.stream = new RotatingFileStream(s);
if (!s.closeOnExit) {
s.closeOnExit = true;
}
break;
case 'raw':
if (!s.closeOnExit) {
s.closeOnExit = false;
}
break;
default:
throw new TypeError('unknown stream type "' + s.type + '"');
}
if (s.reemitErrorEvents && typeof (s.stream.on) === 'function') {
// TODO: When we have `<logger>.close()`, it should remove event
// listeners to not leak Logger instances.
s.stream.on('error', function onStreamError(err) {
self.emit('error', err, s);
});
}
self.streams.push(s);
delete self.haveNonRawStreams; // reset
}
/**
* Add serializers
*
* @param serializers {Object} Optional. Object mapping log record field names
* to serializing functions. See README.md for details.
*/
Logger.prototype.addSerializers = function addSerializers(serializers) {
var self = this;
if (!self.serializers) {
self.serializers = {};
}
Object.keys(serializers).forEach(function (field) {
var serializer = serializers[field];
if (typeof (serializer) !== 'function') {
throw new TypeError(format(
'invalid serializer for "%s" field: must be a function',
field));
} else {
self.serializers[field] = serializer;
}
});
}
/**
* Create a child logger, typically to add a few log record fields.
*
* This can be useful when passing a logger to a sub-component, e.g. a
* 'wuzzle' component of your service:
*
* var wuzzleLog = log.child({component: 'wuzzle'})
* var wuzzle = new Wuzzle({..., log: wuzzleLog})
*
* Then log records from the wuzzle code will have the same structure as
* the app log, *plus the component='wuzzle' field*.
*
* @param options {Object} Optional. Set of options to apply to the child.
* All of the same options for a new Logger apply here. Notes:
* - The parent's streams are inherited and cannot be removed in this
* call. Any given `streams` are *added* to the set inherited from
* the parent.
* - The parent's serializers are inherited, though can effectively be
* overwritten by using duplicate keys.
* - Can use `level` to set the level of the streams inherited from
* the parent. The level for the parent is NOT affected.
* @param simple {Boolean} Optional. Set to true to assert that `options`
* (a) only add fields (no config) and (b) no serialization handling is
* required for them. IOW, this is a fast path for frequent child
* creation. See 'tools/timechild.js' for numbers.
*/
Logger.prototype.child = function (options, simple) {
return new (this.constructor)(this, options || {}, simple);
}
/**
* A convenience method to reopen 'file' streams on a logger. This can be
* useful with external log rotation utilities that move and re-open log files
* (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities
* typically have rotation options to copy-and-truncate the log file, but
* you may not want to use that. An alternative is to do this in your
* application:
*
* var log = bunyan.createLogger(...);
* ...
* process.on('SIGUSR2', function () {
* log.reopenFileStreams();
* });
* ...
*
* See <https://github.com/trentm/node-bunyan/issues/104>.
*/
Logger.prototype.reopenFileStreams = function () {
var self = this;
self.streams.forEach(function (s) {
if (s.type === 'file') {
if (s.stream) {
// Not sure if typically would want this, or more immediate
// `s.stream.destroy()`.
s.stream.end();
s.stream.destroySoon();
delete s.stream;
}
s.stream = fs.createWriteStream(s.path,
{flags: 'a', encoding: 'utf8'});
s.stream.on('error', function (err) {
self.emit('error', err, s);
});
}
});
};
/* BEGIN JSSTYLED */
/**
* Close this logger.
*
* This closes streams (that it owns, as per 'endOnClose' attributes on
* streams), etc. Typically you **don't** need to bother calling this.
Logger.prototype.close = function () {
if (this._closed) {
return;
}
if (!this._isSimpleChild) {
self.streams.forEach(function (s) {
if (s.endOnClose) {
xxx('closing stream s:', s);
s.stream.end();
s.endOnClose = false;
}
});
}
this._closed = true;
}
*/
/* END JSSTYLED */
/**
* Get/set the level of all streams on this logger.
*
* Get Usage:
* // Returns the current log level (lowest level of all its streams).
* log.level() -> INFO
*
* Set Usage:
* log.level(INFO) // set all streams to level INFO
* log.level('info') // can use 'info' et al aliases
*/
Logger.prototype.level = function level(value) {
if (value === undefined) {
return this._level;
}
var newLevel = resolveLevel(value);
var len = this.streams.length;
for (var i = 0; i < len; i++) {
this.streams[i].level = newLevel;
}
this._level = newLevel;
}
/**
* Get/set the level of a particular stream on this logger.
*
* Get Usage:
* // Returns an array of the levels of each stream.
* log.levels() -> [TRACE, INFO]
*
* // Returns a level of the identified stream.
* log.levels(0) -> TRACE // level of stream at index 0
* log.levels('foo') // level of stream with name 'foo'
*
* Set Usage:
* log.levels(0, INFO) // set level of stream 0 to INFO
* log.levels(0, 'info') // can use 'info' et al aliases
* log.levels('foo', WARN) // set stream named 'foo' to WARN
*
* Stream names: When streams are defined, they can optionally be given
* a name. For example,
* log = new Logger({
* streams: [
* {
* name: 'foo',
* path: '/var/log/my-service/foo.log'
* level: 'trace'
* },
* ...
*
* @param name {String|Number} The stream index or name.
* @param value {Number|String} The level value (INFO) or alias ('info').
* If not given, this is a 'get' operation.
* @throws {Error} If there is no stream with the given name.
*/
Logger.prototype.levels = function levels(name, value) {
if (name === undefined) {
assert.equal(value, undefined);
return this.streams.map(
function (s) { return s.level });
}
var stream;
if (typeof (name) === 'number') {
stream = this.streams[name];
if (stream === undefined) {
throw new Error('invalid stream index: ' + name);
}
} else {
var len = this.streams.length;
for (var i = 0; i < len; i++) {
var s = this.streams[i];
if (s.name === name) {
stream = s;
break;
}
}
if (!stream) {
throw new Error(format('no stream with name "%s"', name));
}
}
if (value === undefined) {
return stream.level;
} else {
var newLevel = resolveLevel(value);
stream.level = newLevel;
if (newLevel < this._level) {
this._level = newLevel;
}
}
}
/**
* Apply registered serializers to the appropriate keys in the given fields.
*
* Pre-condition: This is only called if there is at least one serializer.
*
* @param fields (Object) The log record fields.
* @param excludeFields (Object) Optional mapping of keys to `true` for
* keys to NOT apply a serializer.
*/
Logger.prototype._applySerializers = function (fields, excludeFields) {
var self = this;
xxx('_applySerializers: excludeFields', excludeFields);
// Check each serializer against these (presuming number of serializers
// is typically less than number of fields).
Object.keys(this.serializers).forEach(function (name) {
if (fields[name] === undefined ||
(excludeFields && excludeFields[name]))
{
return;
}
xxx('_applySerializers; apply to "%s" key', name)
try {
fields[name] = self.serializers[name](fields[name]);
} catch (err) {
_warn(format('bunyan: ERROR: Exception thrown from the "%s" '
+ 'Bunyan serializer. This should never happen. This is a bug '
+ 'in that serializer function.\n%s',
name, err.stack || err));
fields[name] = format('(Error in Bunyan log "%s" serializer '
+ 'broke field. See stderr for details.)', name);
}
});
}
/**
* Emit a log record.
*
* @param rec {log record}
* @param noemit {Boolean} Optional. Set to true to skip emission
* and just return the JSON string.
*/
Logger.prototype._emit = function (rec, noemit) {
var i;
// Lazily determine if this Logger has non-'raw' streams. If there are
// any, then we need to stringify the log record.
if (this.haveNonRawStreams === undefined) {
this.haveNonRawStreams = false;
for (i = 0; i < this.streams.length; i++) {
if (!this.streams[i].raw) {
this.haveNonRawStreams = true;
break;
}
}
}
// Stringify the object (creates a warning str on error).
var str;
if (noemit || this.haveNonRawStreams) {
str = fastAndSafeJsonStringify(rec) + '\n';
}
if (noemit)
return str;
var level = rec.level;
for (i = 0; i < this.streams.length; i++) {
var s = this.streams[i];
if (s.level <= level) {
xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j',
rec.msg, s.type, s.level, level, rec);
s.stream.write(s.raw ? rec : str);
}
};
return str;
}
/**
* Build a record object suitable for emitting from the arguments
* provided to the a log emitter.
*/
function mkRecord(log, minLevel, args) {
var excludeFields, fields, msgArgs;
if (args[0] instanceof Error) {
// `log.<level>(err, ...)`
fields = {
// Use this Logger's err serializer, if defined.
err: (log.serializers && log.serializers.err
? log.serializers.err(args[0])
: Logger.stdSerializers.err(args[0]))
};
excludeFields = {err: true};
if (args.length === 1) {
msgArgs = [fields.err.message];
} else {
msgArgs = args.slice(1);
}
} else if (typeof (args[0]) !== 'object' || Array.isArray(args[0])) {
// `log.<level>(msg, ...)`
fields = null;
msgArgs = args.slice();
} else if (Buffer.isBuffer(args[0])) { // `log.<level>(buf, ...)`
// Almost certainly an error, show `inspect(buf)`. See bunyan
// issue #35.
fields = null;
msgArgs = args.slice();
msgArgs[0] = util.inspect(msgArgs[0]);
} else { // `log.<level>(fields, msg, ...)`
fields = args[0];
if (fields && args.length === 1 && fields.err &&
fields.err instanceof Error)
{
msgArgs = [fields.err.message];
} else {
msgArgs = args.slice(1);
}
}
// Build up the record object.
var rec = objCopy(log.fields);
var level = rec.level = minLevel;
var recFields = (fields ? objCopy(fields) : null);
if (recFields) {
if (log.serializers) {
log._applySerializers(recFields, excludeFields);
}
Object.keys(recFields).forEach(function (k) {
rec[k] = recFields[k];
});
}
rec.msg = format.apply(log, msgArgs);
if (!rec.time) {
rec.time = (new Date());
}
// Get call source info
if (log.src && !rec.src) {
rec.src = getCaller3Info()
}
rec.v = LOG_VERSION;
return rec;
};
/**
* Build an array that dtrace-provider can use to fire a USDT probe. If we've
* already built the appropriate string, we use it. Otherwise, build the