Files
gridpilot.gg/adapters/automation/config/LoggingConfig.ts

88 lines
2.6 KiB
TypeScript

enum LogLevel {
DEBUG = 'debug',
INFO = 'info',
WARN = 'warn',
ERROR = 'error',
FATAL = 'fatal'
} // TODO move to core
export type LogEnvironment = 'development' | 'production' | 'test';
export interface LoggingEnvironmentConfig {
level: LogLevel; // TODO
prettyPrint: boolean;
fileOutput: boolean;
filePath?: string;
maxFiles?: number;
maxFileSize?: string;
}
/**
* Load logging configuration from environment variables.
*
* Environment variables:
* - NODE_ENV: 'development' | 'production' | 'test' (default: 'development')
* - LOG_LEVEL: Override log level (optional)
* - LOG_FILE_PATH: Path for log files in production (default: './logs/gridpilot')
* - LOG_MAX_FILES: Max rotated files to keep (default: 7)
* - LOG_MAX_SIZE: Max file size before rotation (default: '10m')
*
* @returns LoggingEnvironmentConfig with parsed environment values
*/
export function loadLoggingConfig(): LoggingEnvironmentConfig {
const envValue = process.env.NODE_ENV;
const environment = isValidLogEnvironment(envValue) ? envValue : 'development';
const defaults = getDefaultsForEnvironment(environment);
const levelOverride = process.env.LOG_LEVEL;
const level = isValidLogLevel(levelOverride) ? levelOverride : defaults.level;
return {
level,
prettyPrint: defaults.prettyPrint,
fileOutput: defaults.fileOutput,
filePath: process.env.LOG_FILE_PATH || './logs/gridpilot',
maxFiles: parseIntSafe(process.env.LOG_MAX_FILES, 7),
maxFileSize: process.env.LOG_MAX_SIZE || '10m',
};
}
function getDefaultsForEnvironment(env: LogEnvironment): LoggingEnvironmentConfig {
switch (env) {
case 'development':
return {
level: LogLevel.DEBUG,
prettyPrint: true,
fileOutput: false,
};
case 'production':
return {
level: LogLevel.ERROR,
prettyPrint: false,
fileOutput: true,
};
case 'test':
return {
level: LogLevel.WARN,
prettyPrint: false,
fileOutput: false,
};
}
}
function isValidLogEnvironment(value: string | undefined): value is LogEnvironment {
return value === 'development' || value === 'production' || value === 'test';
}
function isValidLogLevel(value: string | undefined): value is LogLevel {
return value === 'debug' || value === 'info' || value === 'warn' || value === 'error' || value === 'fatal';
}
function parseIntSafe(value: string | undefined, defaultValue: number): number {
if (value === undefined || value === '') {
return defaultValue;
}
const parsed = parseInt(value, 10);
return isNaN(parsed) ? defaultValue : parsed;
}