|
| 1 | +import { config } from '$lib/client/core/config'; |
| 2 | +import type { LoggerContext } from '$lib/shared/logging/types'; |
| 3 | +import { |
| 4 | + enrichContextWithDebugInfo, |
| 5 | + enrichLoggerContextWithSentryTraceId, |
| 6 | +} from '$lib/shared/logging/utils'; |
| 7 | +import type { LogLevelName } from './types'; |
| 8 | +import { logLevelColors, logLevels, logTimestampColors } from './utils'; |
| 9 | + |
| 10 | +export const logger = (function () { |
| 11 | + const createLogger = (methodName: LogLevelName) => { |
| 12 | + return ( |
| 13 | + message: string, |
| 14 | + context: LoggerContext = {}, |
| 15 | + stackLevel: number = 3, |
| 16 | + ) => { |
| 17 | + if (!shouldBeLogged(methodName)) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + const contextClone = enrichLoggerContextWithSentryTraceId(context); |
| 22 | + |
| 23 | + console[methodName]( |
| 24 | + ...createLogPrefixStrings(methodName), |
| 25 | + message, |
| 26 | + '\n', |
| 27 | + config.logger.isDebugContextShown |
| 28 | + ? enrichContextWithDebugInfo( |
| 29 | + contextClone, |
| 30 | + window.location.origin, |
| 31 | + stackLevel, |
| 32 | + ) |
| 33 | + : contextClone, |
| 34 | + ); |
| 35 | + |
| 36 | + // Sentry libraries automatically record breadcrumbs for console logs, |
| 37 | + // so there is not need to manually record them. |
| 38 | + }; |
| 39 | + }; |
| 40 | + |
| 41 | + const logger = Object.keys(logLevels).reduce( |
| 42 | + (acc, methodName) => { |
| 43 | + acc[methodName as LogLevelName] = createLogger( |
| 44 | + methodName as LogLevelName, |
| 45 | + ); |
| 46 | + return acc; |
| 47 | + }, |
| 48 | + {} as Record< |
| 49 | + LogLevelName, |
| 50 | + (message: string, context?: LoggerContext, stackLevel?: number) => void |
| 51 | + >, |
| 52 | + ); |
| 53 | + |
| 54 | + return logger; |
| 55 | +})(); |
| 56 | + |
| 57 | +function shouldBeLogged(logLevel: LogLevelName): boolean { |
| 58 | + const requestedLogLevel = logLevels[logLevel]; |
| 59 | + const minLogLevel = logLevels[config.logger.minLogLevel as LogLevelName]; |
| 60 | + |
| 61 | + return requestedLogLevel >= minLogLevel; |
| 62 | +} |
| 63 | + |
| 64 | +function createLogPrefixStrings(logLevel: LogLevelName): string[] { |
| 65 | + const currentUtcTime = new Date().toISOString(); |
| 66 | + const logTimestampColor = logTimestampColors[logLevel]; |
| 67 | + const logLevelColor = logLevelColors[logLevel]; |
| 68 | + const logLevelCommonStyles = |
| 69 | + 'font-weight: bold; padding: 2px 4px; border-radius: 2px;'; |
| 70 | + |
| 71 | + return [ |
| 72 | + `%c[${currentUtcTime}]%c\t%c${logLevel}%c\t:`, |
| 73 | + `color: ${logTimestampColor.color}; font-weight: bold;`, |
| 74 | + '', |
| 75 | + `background-color: ${logLevelColor.backgroundColor}; color: ${logLevelColor.color}; ${logLevelCommonStyles}`, |
| 76 | + '', |
| 77 | + ]; |
| 78 | +} |
0 commit comments