Merged in chore/create-logger-tests (pull request #2996)
Tests for common/logger * chore: add tests for createLogger * chore: add tests for createLogger Approved-by: Linus Flood
This commit is contained in:
67
packages/common/logger/createLogger/index.ts
Normal file
67
packages/common/logger/createLogger/index.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import * as Sentry from "@sentry/nextjs"
|
||||
import { flatten } from "flat"
|
||||
|
||||
import { minimumLogLevel } from "./minimumLogLevel"
|
||||
import { shouldLog } from "./shouldLog"
|
||||
|
||||
import type { logLevels } from "./logLevels"
|
||||
|
||||
function getLogValue(args: unknown[]): Record<string, unknown> | undefined {
|
||||
if (!args || args.length === 0) {
|
||||
return undefined
|
||||
}
|
||||
if (args.length === 1 && typeof args[0] === "object") {
|
||||
return (args[0] as Record<string, unknown>) ?? undefined
|
||||
}
|
||||
if (args.length === 1) {
|
||||
return { value: args[0] }
|
||||
}
|
||||
return flatten(args)
|
||||
}
|
||||
|
||||
export function createLogger(loggerPrefix: string | (() => Promise<string>)) {
|
||||
const asyncWrapper: () => Promise<string> =
|
||||
typeof loggerPrefix === "string" ? async () => loggerPrefix : loggerPrefix
|
||||
|
||||
const getLoggerPrefix = async () => {
|
||||
const prefix = await asyncWrapper()
|
||||
if (!prefix) {
|
||||
return ""
|
||||
}
|
||||
|
||||
return `[${prefix}]`
|
||||
}
|
||||
|
||||
async function log(
|
||||
level: (typeof logLevels)[number],
|
||||
message: string,
|
||||
...args: unknown[]
|
||||
) {
|
||||
if (!shouldLog(level, minimumLogLevel)) {
|
||||
return
|
||||
}
|
||||
|
||||
const logValue = getLogValue(args)
|
||||
|
||||
Sentry.logger[level](
|
||||
`${await getLoggerPrefix()} ${message}`.trim(),
|
||||
logValue
|
||||
)
|
||||
console[level](`${await getLoggerPrefix()} ${message}`.trim(), ...args)
|
||||
}
|
||||
|
||||
return {
|
||||
async debug(message: string, ...args: unknown[]): Promise<void> {
|
||||
await log("debug", message, ...args)
|
||||
},
|
||||
async info(message: string, ...args: unknown[]): Promise<void> {
|
||||
await log("info", message, ...args)
|
||||
},
|
||||
async warn(message: string, ...args: unknown[]): Promise<void> {
|
||||
await log("warn", message, ...args)
|
||||
},
|
||||
async error(message: string, ...args: unknown[]): Promise<void> {
|
||||
await log("error", message, ...args)
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user