|
| 1 | +import { EventProcessor, Hub, Integration, Severity } from '@sentry/types'; |
| 2 | +import { getGlobalObject } from '@sentry/utils/misc'; |
| 3 | +import { fill, normalize } from '@sentry/utils/object'; |
| 4 | +import { safeJoin } from '@sentry/utils/string'; |
| 5 | + |
| 6 | +const global = getGlobalObject<Window | NodeJS.Global>(); |
| 7 | + |
| 8 | +/** Send Console API calls as Sentry Events */ |
| 9 | +export class CaptureConsole implements Integration { |
| 10 | + /** |
| 11 | + * @inheritDoc |
| 12 | + */ |
| 13 | + public name: string = CaptureConsole.id; |
| 14 | + |
| 15 | + /** |
| 16 | + * @inheritDoc |
| 17 | + */ |
| 18 | + public static id: string = 'CaptureConsole'; |
| 19 | + |
| 20 | + /** |
| 21 | + * @inheritDoc |
| 22 | + */ |
| 23 | + private readonly _levels: string[] = ['log', 'info', 'warn', 'error', 'debug', 'assert']; |
| 24 | + |
| 25 | + /** |
| 26 | + * @inheritDoc |
| 27 | + */ |
| 28 | + public constructor(options: { levels?: string[] } = {}) { |
| 29 | + if (options.levels) { |
| 30 | + this._levels = options.levels; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @inheritDoc |
| 36 | + */ |
| 37 | + public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { |
| 38 | + if (!('console' in global)) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + this._levels.forEach(function(level: string): void { |
| 43 | + if (!(level in global.console)) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + fill(global.console, level, function(originalConsoleLevel: () => any): any { |
| 48 | + // tslint:disable-next-line:only-arrow-functions |
| 49 | + return function(...args: any[]): any { |
| 50 | + const hub = getCurrentHub(); |
| 51 | + |
| 52 | + if (hub.getIntegration(CaptureConsole)) { |
| 53 | + hub.withScope(scope => { |
| 54 | + scope.setLevel(Severity.fromString(level)); |
| 55 | + scope.setExtra('arguments', normalize(args, 3)); |
| 56 | + scope.addEventProcessor(event => { |
| 57 | + event.logger = 'console'; |
| 58 | + if (event.sdk) { |
| 59 | + event.sdk = { |
| 60 | + ...event.sdk, |
| 61 | + integrations: [...(event.sdk.integrations || []), 'console'], |
| 62 | + }; |
| 63 | + } |
| 64 | + return event; |
| 65 | + }); |
| 66 | + |
| 67 | + let message = safeJoin(args, ' '); |
| 68 | + if (level === 'assert') { |
| 69 | + if (args[0] === false) { |
| 70 | + message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`; |
| 71 | + scope.setExtra('arguments', normalize(args.slice(1), 3)); |
| 72 | + hub.captureMessage(message); |
| 73 | + } |
| 74 | + } else { |
| 75 | + hub.captureMessage(message); |
| 76 | + } |
| 77 | + }); |
| 78 | + } |
| 79 | + |
| 80 | + // this fails for some browsers. :( |
| 81 | + if (originalConsoleLevel) { |
| 82 | + Function.prototype.apply.call(originalConsoleLevel, global.console, args); |
| 83 | + } |
| 84 | + }; |
| 85 | + }); |
| 86 | + }); |
| 87 | + } |
| 88 | +} |
0 commit comments