-
Notifications
You must be signed in to change notification settings - Fork 43
/
jsnlog.ts
1226 lines (1027 loc) · 47.4 KB
/
jsnlog.ts
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
/// <reference path="Definitions/jsnlog_interfaces.d.ts"/>
import JSNLogAppender = JL.JSNLogAppender
import JSNLogAppenderOptions = JL.JSNLogAppenderOptions
import JSNLogAjaxAppender = JL.JSNLogAjaxAppender
import JSNLogAjaxAppenderOptions = JL.JSNLogAjaxAppenderOptions
import JSNLogConsoleAppender = JL.JSNLogConsoleAppender
import JSNLogFilterOptions = JL.JSNLogFilterOptions
import JSNLogLogger = JL.JSNLogLogger
import JSNLogLoggerOptions = JL.JSNLogLoggerOptions
import JSNLogOptions = JL.JSNLogOptions
function JL(loggerName?: string): JSNLogLogger
{
// If name is empty, return the root logger
if (!loggerName)
{
return JL.__;
}
// Implements Array.reduce. JSNLog supports IE8+ and reduce is not supported in that browser.
// Same interface as the standard reduce, except that
if (!Array.prototype.reduce)
{
Array.prototype.reduce = function (callback: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue?: any)
{
var previousValue = initialValue;
for (var i = 0; i < this.length; i++)
{
previousValue = callback(previousValue, this[i], i, this);
}
return previousValue;
};
}
var accumulatedLoggerName = '';
var logger: JL.Logger = ('.' + loggerName).split('.').reduce(
function (prev: JL.Logger, curr: string, idx: number, arr: string[])
{
// if loggername is a.b.c, than currentLogger will be set to the loggers
// root (prev: JL, curr: '')
// a (prev: JL.__, curr: 'a')
// a.b (prev: JL.__.__a, curr: 'b')
// a.b.c (prev: JL.__.__a.__a.b, curr: 'c')
// Note that when a new logger name is encountered (such as 'a.b.c'),
// a new logger object is created and added as a property to the parent ('a.b').
// The root logger is added as a property of the JL object itself.
// It is essential that the name of the property containing the child logger
// contains the full 'path' name of the child logger ('a.b.c') instead of
// just the bit after the last period ('c').
// This is because the parent inherits properties from its ancestors.
// So if the root has a child logger 'c' (stored in a property 'c' of the root logger),
// then logger 'a.b' has that same property 'c' through inheritance.
// The names of the logger properties start with __, so the root logger
// (which has name ''), has a nice property name '__'.
// accumulatedLoggerName evaluates false ('' is falsy) in first iteration when prev is the root logger.
// accumulatedLoggerName will be the logger name corresponding with the logger in currentLogger.
// Keep in mind that the currentLogger may not be defined yet, so can't get the name from
// the currentLogger object itself.
if (accumulatedLoggerName)
{
accumulatedLoggerName += '.' + curr;
} else
{
accumulatedLoggerName = curr;
}
var currentLogger = prev['__' + accumulatedLoggerName];
// If the currentLogger (or the actual logger being sought) does not yet exist,
// create it now.
if (currentLogger === undefined)
{
// Set the prototype of the Logger constructor function to the parent of the logger
// to be created. This way, __proto of the new logger object will point at the parent.
// When logger.level is evaluated and is not present, the JavaScript runtime will
// walk down the prototype chain to find the first ancestor with a level property.
//
// Note that prev at this point refers to the parent logger.
JL.Logger.prototype = prev;
currentLogger = new JL.Logger(accumulatedLoggerName);
prev['__' + accumulatedLoggerName] = currentLogger;
}
return currentLogger;
}, JL.__);
return logger;
}
module JL
{
export var enabled: boolean;
export var maxMessages: number;
export var defaultAjaxUrl: string;
export var clientIP: string;
export var defaultBeforeSend: any;
export var serialize: any;
// Initialise requestId to empty string. If you don't do this and the user
// does not set it via setOptions, then the JSNLog-RequestId header will
// have value "undefined", which doesn't look good in a log.
//
// Note that you always want to send a requestId as part of log requests,
// otherwise the server side component doesn't know this is a log request
// and may create a new request id for the log request, causing confusion
// in the log.
export var requestId: string = '';
// Number uniquely identifying every log entry within the request.
export var entryId: number = 0;
// Allow property injection of these classes, to enable unit testing
export var _createXMLHttpRequest = function () { return new XMLHttpRequest(); };
export var _getTime = function () { return (new Date).getTime(); };
export var _console = console;
// ----- private variables
export var _appenderNames: string[] = [];
/**
Copies the value of a property from one object to the other.
This is used to copy property values as part of setOption for loggers and appenders.
Because loggers inherit property values from their parents, it is important never to
create a property on a logger if the intent is to inherit from the parent.
Copying rules:
1) if the from property is undefined (for example, not mentioned in a JSON object), the
to property is not affected at all.
2) if the from property is null, the to property is deleted (so the logger will inherit from
its parent).
3) Otherwise, the from property is copied to the to property.
*/
function copyProperty(propertyName: string, from: any, to: any): void
{
if (from[propertyName] === undefined) { return; }
if (from[propertyName] === null) { delete to[propertyName]; return; }
to[propertyName] = from[propertyName];
}
/**
Returns true if a log should go ahead.
Does not check level.
@param filters
Filters that determine whether a log can go ahead.
*/
function allow(filters: JSNLogFilterOptions): boolean
{
// If enabled is not null or undefined, then if it is false, then return false
// Note that undefined==null (!)
if (!(JL.enabled == null))
{
if (!JL.enabled) { return false; }
}
// If the regex contains a bug, that will throw an exception.
// Ignore this, and pass the log item (better too much than too little).
try
{
if (filters.userAgentRegex)
{
if (!new RegExp(filters.userAgentRegex).test(navigator.userAgent)) { return false; }
}
} catch (e) { }
try
{
if (filters.ipRegex && JL.clientIP)
{
if (!new RegExp(filters.ipRegex).test(JL.clientIP)) { return false; }
}
} catch (e) { }
return true;
}
/**
Returns true if a log should go ahead, based on the message.
@param filters
Filters that determine whether a log can go ahead.
@param message
Message to be logged.
*/
function allowMessage(filters: JSNLogFilterOptions, message: string): boolean
{
// If the regex contains a bug, that will throw an exception.
// Ignore this, and pass the log item (better too much than too little).
try
{
if (filters.disallow)
{
if (new RegExp(filters.disallow).test(message)) { return false; }
}
} catch (e) { }
return true;
}
// If logObject is a function, the function is evaluated (without parameters)
// and the result returned.
// Otherwise, logObject itself is returned.
function stringifyLogObjectFunction(logObject: any): any
{
if (typeof logObject == "function")
{
if (logObject instanceof RegExp)
{
return logObject.toString();
}
else
{
return logObject();
}
}
return logObject;
}
class StringifiedLogObject
{
// * msg -
// if the logObject is a scalar (after possible function evaluation), this is set to
// string representing the scalar. Otherwise it is left undefined.
// * meta -
// if the logObject is an object (after possible function evaluation), this is set to
// that object. Otherwise it is left undefined.
// * finalString -
// This is set to the string representation of logObject (after possible function evaluation),
// regardless of whether it is an scalar or an object. An object is stringified to a JSON string.
// Note that you can't call this field "final", because as some point this was a reserved
// JavaScript keyword and using final trips up some minifiers.
constructor(public msg?: string, public meta?: any, public finalString?: string) { }
}
// Takes a logObject, which can be
// * a scalar
// * an object
// * a parameterless function, which returns the scalar or object to log.
// Returns a stringifiedLogObject
function stringifyLogObject(logObject: any): StringifiedLogObject
{
// Note that this works if logObject is null.
// typeof null is object.
// JSON.stringify(null) returns "null".
var actualLogObject = stringifyLogObjectFunction(logObject);
var finalString;
// Note that typeof actualLogObject should not be "function", because that has
// been resolved with stringifyLogObjectFunction.
switch (typeof actualLogObject)
{
case "string":
return new StringifiedLogObject(actualLogObject, null, actualLogObject);
case "number":
finalString = actualLogObject.toString();
return new StringifiedLogObject(finalString, null, finalString);
case "boolean":
finalString = actualLogObject.toString();
return new StringifiedLogObject(finalString, null, finalString);
case "undefined":
return new StringifiedLogObject("undefined", null, "undefined");
case "object":
if ((actualLogObject instanceof RegExp) ||
(actualLogObject instanceof String) ||
(actualLogObject instanceof Number) ||
(actualLogObject instanceof Boolean))
{
finalString = actualLogObject.toString();
return new StringifiedLogObject(finalString, null, finalString);
}
else
{
if (typeof JL.serialize === 'function') {
finalString = JL.serialize.call(this, actualLogObject);
} else {
finalString = JSON.stringify(actualLogObject);
}
// Set the msg field to "" instead of null. Some Winston transports
// assume that the msg field is not null.
return new StringifiedLogObject("", actualLogObject, finalString);
}
default:
return new StringifiedLogObject("unknown", null, "unknown");
}
}
export function setOptions(options: JSNLogOptions): void
{
copyProperty("enabled", options, this);
copyProperty("maxMessages", options, this);
copyProperty("defaultAjaxUrl", options, this);
copyProperty("clientIP", options, this);
copyProperty("requestId", options, this);
copyProperty("defaultBeforeSend", options, this);
copyProperty("serialize", options, this);
return this;
}
export function getAllLevel(): number { return -2147483648; }
export function getTraceLevel(): number { return 1000; }
export function getDebugLevel(): number { return 2000; }
export function getInfoLevel(): number { return 3000; }
export function getWarnLevel(): number { return 4000; }
export function getErrorLevel(): number { return 5000; }
export function getFatalLevel(): number { return 6000; }
export function getOffLevel(): number { return 2147483647; }
function levelToString(level: number): string
{
if (level <= 1000) { return "trace"; }
if (level <= 2000) { return "debug"; }
if (level <= 3000) { return "info"; }
if (level <= 4000) { return "warn"; }
if (level <= 5000) { return "error"; }
return "fatal";
}
// ---------------------
export class Exception
{
public name: string;
public message: string;
// data replaces message. It takes not just strings, but also objects and functions, just like the log function.
// internally, the string representation is stored in the message property (inherited from Error)
//
// inner: inner exception. Can be null or undefined.
constructor(data: any, public inner?: any)
{
this.name = "JL.Exception";
this.message = stringifyLogObject(data).finalString;
}
}
// Derive Exception from Error (a Host object), so browsers
// are more likely to produce a stack trace for it in their console.
//
// Note that instanceof against an object created with this constructor
// will return true in these cases:
// <object> instanceof JL.Exception);
// <object> instanceof Error);
Exception.prototype = <any>new Error();
// ---------------------
export class LogItem
{
// l: level
// m: message
// n: logger name
// t (timeStamp) is number of milliseconds since 1 January 1970 00:00:00 UTC
// u: number uniquely identifying this entry for this request.
//
// Keeping the property names really short, because they will be sent in the
// JSON payload to the server.
constructor(public l: number, public m: string,
public n: string, public t: number, public u: number) { }
}
function newLogItem(levelNbr: number, message: string, loggerName: string): LogItem {
JL.entryId++;
return new LogItem(levelNbr, message, loggerName, JL._getTime(), JL.entryId);
}
// ---------------------
interface ITimer {
id: any;
}
function clearTimer(timer: ITimer): void {
if(timer.id) {
clearTimeout(timer.id);
timer.id = null;
}
}
function setTimer(timer: ITimer, timeoutMs: number, callback: () => void): void {
var that = this;
if(!timer.id) {
timer.id = setTimeout(function () {
// use call to ensure that the this as used inside sendBatch when it runs is the
// same this at this point.
callback.call(that);
}, timeoutMs);
}
}
export class Appender implements JSNLogAppender, JSNLogFilterOptions
{
public level: number = JL.getTraceLevel();
public ipRegex: string;
public userAgentRegex: string;
public disallow: string;
// set to super high level, so if user increases level, level is unlikely to get
// above sendWithBufferLevel
private sendWithBufferLevel: number = 2147483647;
private storeInBufferLevel: number = -2147483648;
private bufferSize: number = 0; // buffering switch off by default
private batchSize: number = 1;
private maxBatchSize: number = 20;
private batchTimeout: number = 2147483647;
private sendTimeout: number = 5000;
// Holds all log items with levels higher than storeInBufferLevel
// but lower than level. These items may never be sent.
private buffer: LogItem[] = [];
// Holds all items that we do want to send, until we have a full
// batch (as determined by batchSize).
private batchBuffer: LogItem[] = [];
// Holds the id of the timer implementing the batch timeout.
// Can be null.
// This is an object, so it can be passed to a method that updated the timer variable.
private batchTimeoutTimer: ITimer = { id: null };
// Holds the id of the timer implementing the send timeout.
// Can be null.
private sendTimeoutTimer: ITimer = { id: null };
// Number of log items that has been skipped due to batch buffer at max size,
// since appender creation or since creation of the last "skipped" warning log entry.
private nbrLogItemsSkipped: number = 0;
// Will be 0 if no log request is outstanding at the moment.
// Otherwise the number of log items in the outstanding request.
private nbrLogItemsBeingSent: number = 0;
// sendLogItems takes an array of log items. It will be called when
// the appender has items to process (such as, send to the server).
// sendLogItems will call successCallback after the items have been successfully sent.
//
// Note that after sendLogItems returns, the appender may truncate
// the LogItem array, so the function has to copy the content of the array
// in some fashion (eg. serialize) before returning.
constructor(
public appenderName: string,
public sendLogItems: (logItems: LogItem[], successCallback: () => void) => void)
{
var emptyNameErrorMessage = "Trying to create an appender without a name or with an empty name";
// This evaluates to true if appenderName is either null or undefined!
// Do not check here if the name is "", because that would stop you creating the
// default appender.
if (appenderName == undefined) {
throw emptyNameErrorMessage;
}
if (JL._appenderNames.indexOf(appenderName) != -1) {
// If user passed in "", that will now have been picked up as a duplicate
// because default appender also uses "".
if (!appenderName) {
throw emptyNameErrorMessage;
}
throw "Multiple appenders use the same name " + appenderName;
}
JL._appenderNames.push(appenderName);
}
private addLogItemsToBuffer(logItems: LogItem[]): void {
// If the batch buffer has reached its maximum limit,
// skip the log item and increase the "skipped items" counter.
if (this.batchBuffer.length >= this.maxBatchSize) {
this.nbrLogItemsSkipped += logItems.length;
return;
}
// If maxMessages is not null or undefined, then decrease it by the batch size.
// This can result in a negative maxMessages.
// Note that undefined==null (!)
//
// Note that we may be sending more messages than the maxMessages limit allows,
// if we stored trace messages. Rationale is the buffer for trace messages is limited,
// and if we cut off at exactly maxMessages, we'd also loose the high severity message
// that caused the trace messages to be sent (unless we cater for this specifically, which
// is more complexity).
//
// If there are multiple appenders sending the same message, maxMessage will be decreased
// by each appender for the same message. This is:
// 1) only appenders know whether a message will actually be sent (based on storeInBufferLevel),
// so the loggers couldn't do this update;
// 2) if you have multiple appenders hitting the same server, this may be what you want.
//
// In most cases there is only 1 appender, so this then doesn't matter.
if (!(JL.maxMessages == null)) {
if (JL.maxMessages < 1) { return; }
JL.maxMessages -= logItems.length;
}
this.batchBuffer = this.batchBuffer.concat(logItems);
// If this is the first item in the buffer, set the timer
// to ensure it will be sent within the timeout period.
// If it is not the first item, leave the timer alone so to not to
// increase the timeout for the first item.
//
// To determine if this is the first item, look at the timer variable.
// Do not look at the buffer length, because we also put items in the buffer
// via a concat (bypassing this function).
//
// The setTimer method only sets the timer if it is not already running.
var that = this;
setTimer(this.batchTimeoutTimer, this.batchTimeout, function () {
that.sendBatch.call(that);
});
};
private batchBufferHasOverdueMessages(): boolean {
for (let i: number = 0; i < this.batchBuffer.length; i++) {
let messageAgeMs: number = JL._getTime() - this.batchBuffer[i].t;
if (messageAgeMs > this.batchTimeout) { return true; }
}
return false;
}
// Returns true if no more message will ever be added to the batch buffer,
// but the batch buffer has messages now - so if there are not enough to make up a batch,
// and there is no batch timeout, then they will never be sent. This is especially important if
// maxMessages was reached while jsnlog.js was retrying sending messages to the server.
private batchBufferHasStrandedMessage(): boolean {
return (!(JL.maxMessages == null)) && (JL.maxMessages < 1) && (this.batchBuffer.length > 0);
}
private sendBatchIfComplete(): void {
if ((this.batchBuffer.length >= this.batchSize) ||
this.batchBufferHasOverdueMessages() ||
this.batchBufferHasStrandedMessage()) {
this.sendBatch();
}
}
private onSendingEnded(): void {
clearTimer(this.sendTimeoutTimer);
this.nbrLogItemsBeingSent = 0;
this.sendBatchIfComplete();
}
public setOptions(options: JSNLogAppenderOptions): JSNLogAppender
{
copyProperty("level", options, this);
copyProperty("ipRegex", options, this);
copyProperty("userAgentRegex", options, this);
copyProperty("disallow", options, this);
copyProperty("sendWithBufferLevel", options, this);
copyProperty("storeInBufferLevel", options, this);
copyProperty("bufferSize", options, this);
copyProperty("batchSize", options, this);
copyProperty("maxBatchSize", options, this);
copyProperty("batchTimeout", options, this);
copyProperty("sendTimeout", options, this);
if (this.bufferSize < this.buffer.length) { this.buffer.length = this.bufferSize; }
if (this.maxBatchSize < this.batchSize) {
throw new JL.Exception({
"message": "maxBatchSize cannot be smaller than batchSize",
"maxBatchSize": this.maxBatchSize,
"batchSize": this.batchSize
});
}
return this;
}
/**
Called by a logger to log a log item.
If in response to this call one or more log items need to be processed
(eg., sent to the server), this method calls this.sendLogItems
with an array with all items to be processed.
Note that the name and parameters of this function must match those of the log function of
a Winston transport object, so that users can use these transports as appenders.
That is why there are many parameters that are not actually used by this function.
level - string with the level ("trace", "debug", etc.) Only used by Winston transports.
msg - human readable message. Undefined if the log item is an object. Only used by Winston transports.
meta - log object. Always defined, because at least it contains the logger name. Only used by Winston transports.
callback - function that is called when the log item has been logged. Only used by Winston transports.
levelNbr - level as a number. Not used by Winston transports.
message - log item. If the user logged an object, this is the JSON string. Not used by Winston transports.
loggerName: name of the logger. Not used by Winston transports.
*/
public log(
level: string, msg: string, meta: any, callback: () => void,
levelNbr: number, message: string, loggerName: string): void
{
var logItem: LogItem;
if (!allow(this)) { return; }
if (!allowMessage(this, message)) { return; }
if (levelNbr < this.storeInBufferLevel)
{
// Ignore the log item completely
return;
}
logItem = newLogItem(levelNbr, message, loggerName);
if (levelNbr < this.level)
{
// Store in the hold buffer. Do not send.
if (this.bufferSize > 0)
{
this.buffer.push(logItem);
// If we exceeded max buffer size, remove oldest item
if (this.buffer.length > this.bufferSize)
{
this.buffer.shift();
}
}
return;
}
// Want to send the item
this.addLogItemsToBuffer([logItem]);
if (levelNbr >= this.sendWithBufferLevel) {
// Want to send the contents of the buffer.
//
// Send the buffer AFTER sending the high priority item.
// If you were to send the high priority item after the buffer,
// if we're close to maxMessages or maxBatchSize,
// then the trace messages in the buffer could crowd out the actual high priority item.
if (this.buffer.length)
{
this.addLogItemsToBuffer(this.buffer);
this.buffer.length = 0;
}
}
this.sendBatchIfComplete();
};
// Processes the batch buffer
//
// Make this public, so it can be called from outside the library,
// when the page is unloaded.
public sendBatch(): void
{
// Do not clear the batch timer if you don't go ahead here because
// a send is already in progress. Otherwise the messages that were stopped from going out
// may get ignored because the batch timer never went off.
if (this.nbrLogItemsBeingSent > 0) {
return;
}
clearTimer(this.batchTimeoutTimer);
if (this.batchBuffer.length == 0)
{
return;
}
// Decided at this point to send contents of the buffer
this.nbrLogItemsBeingSent = this.batchBuffer.length;
var that = this;
setTimer(this.sendTimeoutTimer, this.sendTimeout, function () {
that.onSendingEnded.call(that);
});
this.sendLogItems(this.batchBuffer, function () {
// Log entries have been successfully sent to server
// Remove the first (nbrLogItemsBeingSent) items in the batch buffer, because they are the ones
// that were sent.
that.batchBuffer.splice(0, that.nbrLogItemsBeingSent);
// If items had to be skipped, add a WARN message
if (that.nbrLogItemsSkipped > 0) {
that.batchBuffer.push(
newLogItem(getWarnLevel(),
"Lost " + that.nbrLogItemsSkipped + " messages. Either connection with the server was down or logging was disabled via the enabled option. Reduce lost messages by increasing the ajaxAppender option maxBatchSize.",
that.appenderName));
that.nbrLogItemsSkipped = 0;
}
that.onSendingEnded.call(that);
});
}
}
// ---------------------
export class AjaxAppender extends Appender implements JSNLogAjaxAppender
{
private url: string;
private beforeSend: any;
private xhr: XMLHttpRequest;
public setOptions(options: JSNLogAjaxAppenderOptions): JSNLogAjaxAppender
{
copyProperty("url", options, this);
copyProperty("beforeSend", options, this);
super.setOptions(options);
return this;
}
public sendLogItemsAjax(logItems: LogItem[], successCallback: () => void): void
{
// JSON.stringify is only supported on IE8+
// Use try-catch in case we get an exception here.
//
// The "r" field is now obsolete. When writing a server side component,
// read the HTTP header "JSNLog-RequestId"
// to get the request id.
//
// The .Net server side component
// now uses the JSNLog-RequestId HTTP Header, because this allows it to
// detect whether the incoming request has a request id.
// If the request id were in the json payload, it would have to read the json
// from the stream, interfering with normal non-logging requests.
//
// To see what characters you can use in the HTTP header, visit:
// http://stackoverflow.com/questions/3561381/custom-http-headers-naming-conventions/3561399#3561399
//
// It needs this ability, so users of NLog can set a requestId variable in NLog
// before the server side component tries to log the client side log message
// through an NLog logger.
// Unlike Log4Net, NLog doesn't allow you to register an object whose ToString()
// is only called when it tries to log something, so the requestId has to be
// determined right at the start of request processing.
try
{
// Do not send logs, if JL.enabled is set to false.
//
// Do not call successCallback here. After each timeout, jsnlog will retry sending the message.
// If jsnlog gets re-enabled, it will then log the number of messages logged.
// If it doesn't get re-enabled, amount of cpu cycles wasted is minimal.
if (!allow(this)) { return; }
// If a request is in progress, abort it.
// Otherwise, it may call the success callback, which will be very confusing.
// It may also stop the inflight request from resulting in a log at the server.
if (this.xhr && (this.xhr.readyState != 0) && (this.xhr.readyState != 4)) {
this.xhr.abort();
}
// Because a react-native XMLHttpRequest cannot be reused it needs to be recreated with each request
this.xhr = JL._createXMLHttpRequest();
// Only determine the url right before you send a log request.
// Do not set the url when constructing the appender.
//
// This is because the server side component sets defaultAjaxUrl
// in a call to setOptions, AFTER the JL object and the default appender
// have been created.
var ajaxUrl: string = "/jsnlog.logger";
// This evaluates to true if defaultAjaxUrl is null or undefined
if (!(JL.defaultAjaxUrl == null))
{
ajaxUrl = JL.defaultAjaxUrl;
}
if (this.url)
{
ajaxUrl = this.url;
}
this.xhr.open('POST', ajaxUrl);
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.setRequestHeader('JSNLog-RequestId', JL.requestId);
var that = this;
this.xhr.onreadystatechange = function () {
// On most browsers, if the request fails (eg. internet is gone),
// it will set xhr.readyState == 4 and xhr.status != 200 (0 if request could not be sent) immediately.
// However, Edge and IE will not change the readyState at all if the internet goes away while waiting
// for a response.
// Some servers will return a 204 (success, no content) when the JSNLog endpoint
// returns the empty response. So check on any code in the 2.. range, not just 200.
if ((that.xhr.readyState == 4) && (that.xhr.status >= 200 && that.xhr.status < 300)) {
successCallback();
}
};
var json: any = {
r: JL.requestId,
lg: logItems
};
// call beforeSend callback
// first try the callback on the appender
// then the global defaultBeforeSend callback
if (typeof this.beforeSend === 'function') {
this.beforeSend.call(this, this.xhr, json);
} else if (typeof JL.defaultBeforeSend === 'function') {
JL.defaultBeforeSend.call(this, this.xhr, json);
}
var finalmsg = JSON.stringify(json);
this.xhr.send(finalmsg);
} catch (e) { }
}
constructor(appenderName: string)
{
super(appenderName, AjaxAppender.prototype.sendLogItemsAjax);
}
}
// ---------------------
export class ConsoleAppender extends Appender implements JSNLogConsoleAppender
{
private clog(logEntry: string)
{
JL._console.log(logEntry);
}
private cerror(logEntry: string)
{
if (JL._console.error)
{
JL._console.error(logEntry);
} else
{
this.clog(logEntry);
}
}
private cwarn(logEntry: string)
{
if (JL._console.warn)
{
JL._console.warn(logEntry);
} else
{
this.clog(logEntry);
}
}
private cinfo(logEntry: string)
{
if (JL._console.info)
{
JL._console.info(logEntry);
} else
{
this.clog(logEntry);
}
}
// IE11 has a console.debug function. But its console doesn't have
// the option to show/hide debug messages (the same way Chrome and FF do),
// even though it does have such buttons for Error, Warn, Info.
//
// For now, this means that debug messages can not be hidden on IE.
// Live with this, seeing that it works fine on FF and Chrome, which
// will be much more popular with developers.
private cdebug(logEntry: string)
{
if (JL._console.debug)
{
JL._console.debug(logEntry);
} else
{
this.cinfo(logEntry);
}
}
public sendLogItemsConsole(logItems: LogItem[], successCallback: () => void): void
{
try
{
// Do not send logs, if JL.enabled is set to false
//
// Do not call successCallback here. After each timeout, jsnlog will retry sending the message.
// If jsnlog gets re-enabled, it will then log the number of messages logged.
// If it doesn't get re-enabled, amount of cpu cycles wasted is minimal.
if (!allow(this)) { return; }
if (!JL._console) { return; }
var i;
for (i = 0; i < logItems.length; ++i)
{
var li = logItems[i];
var msg = li.n + ": " + li.m;
// Only log the timestamp if we're on the server
// (window is undefined). On the browser, the user
// sees the log entry probably immediately, so in that case
// the timestamp is clutter.
if (typeof window === 'undefined')
{
msg = new Date(li.t) + " | " + msg;
}
if (li.l <= JL.getDebugLevel())
{
this.cdebug(msg);
} else if (li.l <= JL.getInfoLevel())
{
this.cinfo(msg);
} else if (li.l <= JL.getWarnLevel())
{
this.cwarn(msg);
} else
{
this.cerror(msg);
}
}
} catch (e)
{
}
successCallback();
}
constructor(appenderName: string)
{
super(appenderName, ConsoleAppender.prototype.sendLogItemsConsole);
}
}
// --------------------
export class Logger implements JSNLogLogger, JSNLogFilterOptions
{
public appenders: Appender[];
// Array of strings with regular expressions. Used to stop duplicate messages.
// If a message matches a regex
// that has been matched before, that message will not be sent.
public onceOnly: string[];
public level: number;
public userAgentRegex: string;
public ipRegex: string;
public disallow: string;
// Used to remember which regexes in onceOnly have been successfully
// matched against a message. Index into this array is same as index
// in onceOnly of the corresponding regex.
// When a regex has never been matched, the corresponding entry in this
// array is undefined, which is falsey.
private seenRegexes: boolean[];
constructor(public loggerName: string)
{
// Create seenRexes, otherwise this logger will use the seenRexes
// of its parent via the prototype chain.
this.seenRegexes = [];
}
public setOptions(options: JSNLogLoggerOptions): JSNLogLogger
{
copyProperty("level", options, this);
copyProperty("userAgentRegex", options, this);
copyProperty("disallow", options, this);
copyProperty("ipRegex", options, this);
copyProperty("appenders", options, this);
copyProperty("onceOnly", options, this);