// Copyright Abridged, Inc. 2021,2024. All Rights Reserved. // Node module: @collabland/common // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT import {Debugger} from 'debug'; import {P, pino} from 'pino'; import { LogLevel, getLogLevelForNamespace, isLogEnabled, redactData, } from './debug.js'; import {getEnvVar} from './env.js'; function getLoggingLevel() { const level = getEnvVar('DEBUG_PINO'); return Object.values(LogLevel).find(l => l === level); } /** * Get a Pino logger if Pino is enabled * @returns */ export function getPinoLogger() { const loggingLevel = getLoggingLevel(); const logger = loggingLevel != null ? pino({level: loggingLevel}, process.stderr) : undefined; return logger; } export function getPinoDebugger( logger: P.Logger, debugFactory: (ns: string) => Debugger, namespace: string, ) { const level = getLogLevelForNamespace(namespace); const child = logger.child({ns: namespace}); const debugFn = ((...args: unknown[]) => { if (!isLogEnabled(namespace)) return; args = redactData(args); let msg = ''; if (typeof args[0] === 'string') { msg = args[0]; args = args.slice(1); } child[level]({}, msg, ...args); }) as Debugger; Object.defineProperty(debugFn, 'enabled', { get: function () { return isLogEnabled(namespace); }, }); debugFn.namespace = namespace; debugFn.extend = (subNamespace: string, delimiter?: string) => debugFactory(namespace + (delimiter ?? ':') + subNamespace); return debugFn; }