UNPKG

2.93 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2010-2014 original author or authors */
2/** @author Brian Cavalier */
3/** @author John Hann */
4
5(function(define) { 'use strict';
6define(function(require) {
7
8 var error = require('./error');
9 var unhandledRejectionsMsg = '[promises] Unhandled rejections: ';
10 var allHandledMsg = '[promises] All previously unhandled rejections have now been handled';
11
12 function ConsoleReporter() {
13 this._previouslyReported = false;
14 }
15
16 ConsoleReporter.prototype = initDefaultLogging();
17
18 ConsoleReporter.prototype.log = function(traces) {
19 if(traces.length === 0) {
20 if(this._previouslyReported) {
21 this._previouslyReported = false;
22 this.msg(allHandledMsg);
23 }
24 return;
25 }
26
27 this._previouslyReported = true;
28 this.groupStart(unhandledRejectionsMsg + traces.length);
29 try {
30 this._log(traces);
31 } finally {
32 this.groupEnd();
33 }
34 };
35
36 ConsoleReporter.prototype._log = function(traces) {
37 for(var i=0; i<traces.length; ++i) {
38 this.warn(error.format(traces[i]));
39 }
40 };
41
42 function initDefaultLogging() {
43 /*jshint maxcomplexity:7*/
44 var log, warn, groupStart, groupEnd;
45
46 if(typeof console === 'undefined') {
47 log = warn = consoleNotAvailable;
48 } else {
49 // Alias console to prevent things like uglify's drop_console option from
50 // removing console.log/error. Unhandled rejections fall into the same
51 // category as uncaught exceptions, and build tools shouldn't silence them.
52 var localConsole = console;
53 if(typeof localConsole.error === 'function'
54 && typeof localConsole.dir === 'function') {
55 warn = function(s) {
56 localConsole.error(s);
57 };
58
59 log = function(s) {
60 localConsole.log(s);
61 };
62
63 if(typeof localConsole.groupCollapsed === 'function') {
64 groupStart = function(s) {
65 localConsole.groupCollapsed(s);
66 };
67 groupEnd = function() {
68 localConsole.groupEnd();
69 };
70 }
71 } else {
72 // IE8 has console.log and JSON, so we can make a
73 // reasonably useful warn() from those.
74 // Credit to webpro (https://github.com/webpro) for this idea
75 // typeof localConsole.log will return 'object' in IE8, so can't test it with === 'function'
76 // Since this is more of a corner case for IE8, I'm ok to check it with !== 'undefined' to reduce complexity
77 if (typeof localConsole.log !== 'undefined' && typeof JSON !== 'undefined') {
78 log = warn = function(x) {
79 if (typeof x !== 'string') {
80 try {
81 x = JSON.stringify(x);
82 } catch (e) {
83 }
84 }
85 localConsole.log(x);
86 };
87 } else {
88 log = warn = consoleNotAvailable;
89 }
90 }
91 }
92
93 return {
94 msg: log,
95 warn: warn,
96 groupStart: groupStart || warn,
97 groupEnd: groupEnd || consoleNotAvailable
98 };
99 }
100
101 function consoleNotAvailable() {}
102
103 return ConsoleReporter;
104
105});
106}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));