|
| 1 | +import { Roarr, logLevels, type LogLevelName } from 'roarr'; |
| 2 | +import callsites from 'callsites'; |
| 3 | +import { config } from '$lib/server/core/config'; |
| 4 | +import type { JsonObject, LoggerLoggingMethodName } from './types'; |
| 5 | + |
| 6 | +export const roarr = (function () { |
| 7 | + const createLogger = (methodName: LoggerLoggingMethodName) => { |
| 8 | + return (message: string, context: JsonObject = {}) => { |
| 9 | + if (!shouldBeLogged(methodName)) { |
| 10 | + return; |
| 11 | + } |
| 12 | + |
| 13 | + Roarr[methodName]( |
| 14 | + config.roarr.isDebugContextShown |
| 15 | + ? enrichContextWithDebugInfo(context) |
| 16 | + : context, |
| 17 | + message, |
| 18 | + ); |
| 19 | + }; |
| 20 | + }; |
| 21 | + |
| 22 | + const roarrLoggingMethodNamesNoOnce = Object.keys(Roarr).filter((property) => |
| 23 | + Object.keys(logLevels).includes(property), |
| 24 | + ) as LoggerLoggingMethodName[]; |
| 25 | + const roarrLoggingMethodNamesOnce = roarrLoggingMethodNamesNoOnce.map( |
| 26 | + (methodName) => `${methodName}Once` as LoggerLoggingMethodName, |
| 27 | + ); |
| 28 | + const roarrLoggingMethodNames = [ |
| 29 | + ...roarrLoggingMethodNamesNoOnce, |
| 30 | + ...roarrLoggingMethodNamesOnce, |
| 31 | + ]; |
| 32 | + const roarrLogger = roarrLoggingMethodNames.reduce( |
| 33 | + (acc, methodName) => { |
| 34 | + acc[methodName] = createLogger(methodName); |
| 35 | + return acc; |
| 36 | + }, |
| 37 | + {} as Record< |
| 38 | + LoggerLoggingMethodName, |
| 39 | + (message: string, context?: JsonObject) => void |
| 40 | + >, |
| 41 | + ); |
| 42 | + |
| 43 | + return roarrLogger; |
| 44 | +})(); |
| 45 | + |
| 46 | +function shouldBeLogged(methodName: LoggerLoggingMethodName): boolean { |
| 47 | + const requestedLogLevelName = methodName.replace('Once', '') as LogLevelName; |
| 48 | + const requestedLogLevel = logLevels[requestedLogLevelName]; |
| 49 | + const minLogLevel = logLevels[config.roarr.minLogLevel as LogLevelName]; |
| 50 | + |
| 51 | + return requestedLogLevel >= minLogLevel; |
| 52 | +} |
| 53 | + |
| 54 | +function enrichContextWithDebugInfo(override: JsonObject = {}): JsonObject { |
| 55 | + return { |
| 56 | + callName: getCallName(), |
| 57 | + fileName: getFileName(), |
| 58 | + ...override, |
| 59 | + }; |
| 60 | +} |
| 61 | + |
| 62 | +function getCallName(): string { |
| 63 | + const typeName = callsites()[3]?.getTypeName() ?? ''; |
| 64 | + const functionName = |
| 65 | + callsites()[3]?.getFunctionName() ?? callsites()[3]?.getMethodName() ?? ''; |
| 66 | + |
| 67 | + if (typeName) { |
| 68 | + return `${typeName}.${functionName}`; |
| 69 | + } |
| 70 | + |
| 71 | + return functionName; |
| 72 | +} |
| 73 | + |
| 74 | +function getFileName(): string { |
| 75 | + const fileName = |
| 76 | + callsites()[3]?.getFileName() ?? callsites()[3]?.getEvalOrigin() ?? ''; |
| 77 | + |
| 78 | + return fileName.replace(config.folders.root, ''); |
| 79 | +} |
0 commit comments