logging.ts•2.35 kB
/**
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
const loggerKey = '__genkit_logger';
const _defaultLogger = {
  shouldLog(targetLevel: string) {
    return LOG_LEVELS.indexOf(this.level) <= LOG_LEVELS.indexOf(targetLevel);
  },
  debug(...args: any) {
    this.shouldLog('debug') && console.debug(...args);
  },
  info(...args: any) {
    this.shouldLog('info') && console.info(...args);
  },
  warn(...args: any) {
    this.shouldLog('warn') && console.warn(...args);
  },
  error(...args: any) {
    this.shouldLog('error') && console.error(...args);
  },
  level: 'info',
};
function getLogger() {
  if (!global[loggerKey]) {
    global[loggerKey] = _defaultLogger;
  }
  return global[loggerKey];
}
class Logger {
  readonly defaultLogger = _defaultLogger;
  init(fn: any) {
    global[loggerKey] = fn;
  }
  info(...args: any) {
    // eslint-disable-next-line prefer-spread
    getLogger().info.apply(getLogger(), args);
  }
  debug(...args: any) {
    // eslint-disable-next-line prefer-spread
    getLogger().debug.apply(getLogger(), args);
  }
  error(...args: any) {
    // eslint-disable-next-line prefer-spread
    getLogger().error.apply(getLogger(), args);
  }
  warn(...args: any) {
    // eslint-disable-next-line prefer-spread
    getLogger().warn.apply(getLogger(), args);
  }
  setLogLevel(level: 'error' | 'warn' | 'info' | 'debug') {
    getLogger().level = level;
  }
  logStructured(msg: string, metadata: any) {
    getLogger().info(msg, metadata);
  }
  logStructuredError(msg: string, metadata: any) {
    getLogger().error(msg, metadata);
  }
}
/**
 * Genkit logger.
 *
 * ```ts
 * import { logger } from 'genkit/logging';
 *
 * logger.setLogLevel('debug');
 * ```
 */
export const logger = new Logger();