import { ConsoleLogger, ConsoleLoggerOptions, LoggerService, LogLevel } from '@nestjs/common';

/**
 * 日志
 *
 * @author chitanda
 * @date 2022-01-24 17:01:00
 * @export
 * @class Logger
 * @extends {ConsoleLogger}
 * @implements {LoggerService}
 */
export class Logger extends ConsoleLogger implements LoggerService {
  /**
   * 目前支持的日志输出级别
   *
   * @author chitanda
   * @date 2022-03-25 10:03:22
   * @static
   */
  static loggerLevels: LogLevel[] = ['error', 'warn', 'log', 'debug', 'verbose'];

  constructor(context: string, options: ConsoleLoggerOptions = {}) {
    if (!options.logLevels) {
      options.logLevels = Logger.loggerLevels;
    }
    super(context, options);
  }

  info(message: any, ...optionalParams: any[]) {
    super.log(message, ...optionalParams);
  }

  log(message: any, ...optionalParams: any[]) {
    super.log(message, ...optionalParams);
  }

  error(message: any, ...optionalParams: any[]) {
    super.error(message, ...optionalParams);
  }

  warn(message: any, ...optionalParams: any[]) {
    super.warn(message, ...optionalParams);
  }

  debug(message: any, ...optionalParams: any[]) {
    super.debug(message, ...optionalParams);
  }

  verbose(message: any, ...optionalParams: any[]) {
    super.verbose(message, ...optionalParams);
  }
}

// 全局日志输出
export const logger = new Logger('Global');

/**
 * 设置日志级别
 *
 * @author chitanda
 * @date 2022-03-25 10:03:44
 * @export
 * @param {LogLevel[]} levels
 */
export function setLoggerLevels(levels: LogLevel[]): void {
  if (levels && levels.length > 0) {
    for (let i = 0; i < levels.length; i++) {
      const level = levels[i];
      if (Logger.loggerLevels.indexOf(level) === -1) {
        throw new Error(`未支持的日志级别: ${level}`);
      }
    }
  }
  Logger.loggerLevels = levels;
  logger.setLogLevels(levels);
}
