All files / src/logger/environment shared.ts

100% Statements 58/58
98.18% Branches 54/55
100% Functions 6/6
100% Lines 58/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185              29x 29x 29x                                                       29x 58x         29x 59x   29x   60x   58x                 2x                     29x         60x 60x       60x 58x 58x 42x 14x 14x 13x 2x 2x   13x 13x     1x         28x   16x   4x         58x 58x 19x 39x   5x         58x 58x 16x 12x 4x   4x             60x     29x       49x 35x 35x   24x     3x     1x     5x     2x   1x         21x                 29x 16x 16x         12x     4x 4x      
import { exhaustiveCheck } from '../../utils/common/exhaustive-check.ts';
import type { Logger, LogLevel } from '../definition.ts';
import type { LogFormat } from '../factory.ts';
import { createConsoleByLevelLogger, createConsoleErrorLogger, createConsoleLogLogger } from '../factory.ts';
import { isLogLevel } from '../implementation/level-utils.ts';
import { withLogger } from '../off-logger.ts';
 
const ENV_LOGGER = 'EMITNLOG_LOGGER';
const ENV_LEVEL = 'EMITNLOG_LEVEL';
const ENV_FORMAT = 'EMITNLOG_FORMAT';
 
/**
 * The options for the `fromEnv` function.
 */
export type EnvironmentLoggerOptions = {
  /**
   * The level to use if the environment variable `EMITNLOG_LEVEL` is not set.
   */
  readonly level?: LogLevel;
 
  /**
   * The format to use if the environment variable `EMITNLOG_FORMAT` is not set.
   */
  readonly format?: LogFormat;
 
  /**
   * Returns the fallback logger to use if the environment variable `ENV_LOGGER` is not set.
   *
   * @param level The level to use set, which is `EMITNLOG_LEVEL`, `options.level`, or undefined.
   * @param format The format to use, which is `EMITNLOG_FORMAT`, `options.format`, or undefined.
   * @returns The fallback logger to use or undefined.
   */
  readonly fallbackLogger?: (level?: LogLevel, format?: LogFormat) => Logger | undefined;
};
 
type EnvLogger = 'console-log' | 'console-error' | 'console-level' | `file:${string}`;
 
const isEnvLogger = (value: unknown): value is EnvLogger =>
  value === 'console-log' ||
  value === 'console-error' ||
  value === 'console-level' ||
  (typeof value === 'string' && value.startsWith('file:'));
 
const isEnvHolder = (value: unknown): value is { readonly env: Record<string, string | undefined> } =>
  !!value && typeof value === 'object' && 'env' in value && !!value.env && typeof value.env === 'object';
 
export const toEnv = (): Record<string, string | undefined> | undefined => {
  // eslint-disable-next-line no-undef
  if (typeof process !== 'undefined' && isEnvHolder(process)) {
    // eslint-disable-next-line no-undef
    return process.env;
  }
 
  // This still does not work under the current test runner.
  // const meta = import.meta as unknown as { readonly env: Record<string, string | undefined> };
  // if (typeof meta !== 'undefined' && isEnvHolder(meta)) {
  //   return meta.env;
  // }
 
  return undefined;
};
 
type DecodedEnv = {
  readonly envLogger?: EnvLogger;
  readonly envLevel?: LogLevel;
  readonly envFormat?: LogFormat;
  readonly envFile?: string;
  readonly envDatePrefix?: boolean;
};
 
export const decodeEnv = (
  env: Record<string, string | undefined> | undefined,
  options?: EnvironmentLoggerOptions,
): DecodedEnv | undefined => {
  let envLogger: EnvLogger | undefined;
  let envLevel: LogLevel | undefined = options?.level;
  let envFormat: LogFormat | undefined = options?.format;
  let envFile: string | undefined;
  let envDatePrefix: boolean | undefined;
 
  if (env) {
    const envLoggerValue = env[ENV_LOGGER];
    if (isEnvLogger(envLoggerValue)) {
      if (envLoggerValue.startsWith('file:')) {
        let file = envLoggerValue.slice(5);
        if (file) {
          if (file.startsWith('date:')) {
            file = file.slice(5);
            envDatePrefix = true;
          }
          envLogger = envLoggerValue;
          envFile = file;
        } else {
          // eslint-disable-next-line no-undef, no-console
          console.warn(
            `The value of the environment variable '${ENV_LOGGER}' must provide a file path: '${envLoggerValue}'.\nConsult the emitnlog documentation for the list of valid loggers.`,
          );
        }
      } else {
        envLogger = envLoggerValue;
      }
    } else if (envLoggerValue) {
      // eslint-disable-next-line no-undef, no-console
      console.warn(
        `The value of the environment variable '${ENV_LOGGER}' is not a valid logger: '${envLoggerValue}'.\nConsult the emitnlog documentation for the list of valid loggers.`,
      );
    }
 
    const envLevelValue = env[ENV_LEVEL];
    if (isLogLevel(envLevelValue)) {
      envLevel = envLevelValue;
    } else if (envLevelValue) {
      // eslint-disable-next-line no-undef, no-console
      console.warn(
        `The value of the environment variable '${ENV_LEVEL}' is not a valid level: '${envLevelValue}'.\nConsult the emitnlog documentation for the list of valid levels.`,
      );
    }
 
    const envFormatValue = env[ENV_FORMAT];
    if (envFormatValue) {
      if (isLogFormat(envFormatValue)) {
        envFormat = envFormatValue;
      E} else if (envFormatValue) {
        // eslint-disable-next-line no-undef, no-console
        console.warn(
          `The value of the environment variable '${ENV_FORMAT}' is not a valid format: '${envFormatValue}'.\nConsult the emitnlog documentation for the list of valid formats.`,
        );
      }
    }
  }
 
  return envLogger || envLevel || envFormat ? { envLogger, envLevel, envFormat, envFile, envDatePrefix } : undefined;
};
 
export const createLoggerFromEnv = (
  decodedEnv: DecodedEnv | undefined,
  options: EnvironmentLoggerOptions | undefined,
): Logger => {
  if (decodedEnv) {
    const { envLogger, envLevel, envFormat, envFile } = decodedEnv;
    switch (envLogger) {
      case 'console-log':
        return createConsoleLogLogger(envLevel, envFormat);
 
      case 'console-error':
        return createConsoleErrorLogger(envLevel, envFormat);
 
      case 'console-level':
        return createConsoleByLevelLogger(envLevel, envFormat);
 
      case undefined:
        break;
 
      default:
        if (envFile) {
          // eslint-disable-next-line no-undef, no-console
          console.warn(`The file logger is only supported in NodeJS.`);
        }
    }
  }
 
  return withLogger(options?.fallbackLogger?.(decodedEnv?.envLevel, decodedEnv?.envFormat));
};
 
/**
 * Checks if a string is a valid LogFormat.
 *
 * @param value The string to check
 * @returns True if the string is a valid LogFormat, false otherwise
 */
const isLogFormat = (value: unknown): value is LogFormat => {
  const format = value as LogFormat;
  switch (format) {
    case 'plain':
    case 'colorful':
    case 'ndjson':
    case 'json-pretty':
      return true;
 
    default:
      exhaustiveCheck(format);
      return false;
  }
};