-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(utils): Convert Logger class to functions #4863
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,118 +1,99 @@ | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
import { WrappedFunction } from '@sentry/types'; | ||
|
||
import { IS_DEBUG_BUILD } from './flags'; | ||
import { getGlobalObject } from './global'; | ||
import { getGlobalObject, getGlobalSingleton } from './global'; | ||
|
||
// TODO: Implement different loggers for different environments | ||
const global = getGlobalObject<Window | NodeJS.Global>(); | ||
|
||
/** Prefix for logging strings */ | ||
const PREFIX = 'Sentry Logger '; | ||
|
||
export const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert']; | ||
export const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert'] as const; | ||
|
||
type LoggerMethod = (...args: unknown[]) => void; | ||
type LoggerConsoleMethods = Record<typeof CONSOLE_LEVELS[number], LoggerMethod>; | ||
|
||
/** JSDoc */ | ||
interface ExtensibleConsole extends Console { | ||
[key: string]: any; | ||
interface Logger extends LoggerConsoleMethods { | ||
disable(): void; | ||
enable(): void; | ||
} | ||
|
||
/** | ||
* Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods. | ||
* Restores wrapping after the callback completes. | ||
* Temporarily disable sentry console instrumentations. | ||
* | ||
* @param callback The function to run against the original `console` messages | ||
* @returns The results of the callback | ||
*/ | ||
export function consoleSandbox(callback: () => any): any { | ||
export function consoleSandbox<T>(callback: () => T): T { | ||
const global = getGlobalObject<Window>(); | ||
|
||
if (!('console' in global)) { | ||
return callback(); | ||
} | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
const originalConsole = (global as any).console as ExtensibleConsole; | ||
const wrappedLevels: { [key: string]: any } = {}; | ||
const originalConsole = global.console as Console & Record<string, unknown>; | ||
const wrappedLevels: Partial<LoggerConsoleMethods> = {}; | ||
|
||
// Restore all wrapped console methods | ||
CONSOLE_LEVELS.forEach(level => { | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
if (level in (global as any).console && (originalConsole[level] as WrappedFunction).__sentry_original__) { | ||
wrappedLevels[level] = originalConsole[level] as WrappedFunction; | ||
originalConsole[level] = (originalConsole[level] as WrappedFunction).__sentry_original__; | ||
// TODO(v7): Remove this check as it's only needed for Node 6 | ||
const originalWrappedFunc = | ||
originalConsole[level] && (originalConsole[level] as WrappedFunction).__sentry_original__; | ||
if (level in global.console && originalWrappedFunc) { | ||
wrappedLevels[level] = originalConsole[level] as LoggerConsoleMethods[typeof level]; | ||
originalConsole[level] = originalWrappedFunc as Console[typeof level]; | ||
} | ||
}); | ||
|
||
// Perform callback manipulations | ||
const result = callback(); | ||
|
||
// Revert restoration to wrapped state | ||
Object.keys(wrappedLevels).forEach(level => { | ||
originalConsole[level] = wrappedLevels[level]; | ||
}); | ||
|
||
return result; | ||
} | ||
|
||
/** JSDoc */ | ||
class Logger { | ||
/** JSDoc */ | ||
private _enabled: boolean; | ||
|
||
/** JSDoc */ | ||
public constructor() { | ||
this._enabled = false; | ||
} | ||
|
||
/** JSDoc */ | ||
public disable(): void { | ||
this._enabled = false; | ||
} | ||
|
||
/** JSDoc */ | ||
public enable(): void { | ||
this._enabled = true; | ||
} | ||
|
||
/** JSDoc */ | ||
public log(...args: any[]): void { | ||
if (!this._enabled) { | ||
return; | ||
} | ||
consoleSandbox(() => { | ||
global.console.log(`${PREFIX}[Log]:`, ...args); | ||
try { | ||
return callback(); | ||
} finally { | ||
// Revert restoration to wrapped state | ||
Object.keys(wrappedLevels).forEach(level => { | ||
originalConsole[level] = wrappedLevels[level as typeof CONSOLE_LEVELS[number]]; | ||
}); | ||
} | ||
} | ||
|
||
/** JSDoc */ | ||
public warn(...args: any[]): void { | ||
if (!this._enabled) { | ||
return; | ||
} | ||
consoleSandbox(() => { | ||
global.console.warn(`${PREFIX}[Warn]:`, ...args); | ||
function makeLogger(): Logger { | ||
let enabled = false; | ||
const logger: Partial<Logger> = { | ||
enable: () => { | ||
enabled = true; | ||
}, | ||
disable: () => { | ||
enabled = false; | ||
}, | ||
}; | ||
|
||
if (IS_DEBUG_BUILD) { | ||
CONSOLE_LEVELS.forEach(name => { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
logger[name] = (...args: any[]) => { | ||
if (enabled) { | ||
consoleSandbox(() => { | ||
global.console[name](`${PREFIX}[${name}]:`, ...args); | ||
}); | ||
} | ||
}; | ||
}); | ||
} | ||
|
||
/** JSDoc */ | ||
public error(...args: any[]): void { | ||
if (!this._enabled) { | ||
return; | ||
} | ||
consoleSandbox(() => { | ||
global.console.error(`${PREFIX}[Error]:`, ...args); | ||
} else { | ||
CONSOLE_LEVELS.forEach(name => { | ||
logger[name] = () => undefined; | ||
}); | ||
} | ||
} | ||
|
||
const sentryGlobal = global.__SENTRY__ || {}; | ||
const logger = (sentryGlobal.logger as Logger) || new Logger(); | ||
return logger as Logger; | ||
} | ||
|
||
// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used | ||
let logger: Logger; | ||
if (IS_DEBUG_BUILD) { | ||
// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used | ||
sentryGlobal.logger = logger; | ||
global.__SENTRY__ = sentryGlobal; | ||
logger = getGlobalSingleton('logger', makeLogger); | ||
} else { | ||
logger = makeLogger(); | ||
} | ||
|
||
export { logger }; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
as a next step, we can further refactor
consoleSandbox
to take alevel
argument, so we don't have to un-patch and re-patch every single console level every time we call this.