56 lines
2.2 KiB
Go
56 lines
2.2 KiB
Go
package hlog
|
|
|
|
import (
|
|
"git.haelnorr.com/h/golib/env"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// Config holds the configuration settings for the logger.
|
|
// It can be populated from environment variables using ConfigFromEnv
|
|
// or created programmatically.
|
|
type Config struct {
|
|
LogLevel Level `ezconf:"LOG_LEVEL,description:Log level for the logger - trace debug info warn error fatal panic,default:info"`
|
|
LogOutput string `ezconf:"LOG_OUTPUT,description:Output destination for logs - console file or both,default:console"`
|
|
LogDir string `ezconf:"LOG_DIR,description:Directory path for log files,required:when LOG_OUTPUT is file or both"`
|
|
LogFileName string `ezconf:"LOG_FILE_NAME,description:Name of the log file,required:when LOG_OUTPUT is file or both"`
|
|
LogAppend bool `ezconf:"LOG_APPEND,description:Append to existing log file or overwrite,default:true"`
|
|
}
|
|
|
|
// ConfigFromEnv loads logger configuration from environment variables.
|
|
//
|
|
// Environment variables:
|
|
// - LOG_LEVEL: Log level (trace, debug, info, warn, error, fatal, panic) - default: info
|
|
// - LOG_OUTPUT: Output destination (console, file, both) - default: console
|
|
// - LOG_DIR: Directory for log files (required when LOG_OUTPUT is "file" or "both")
|
|
//
|
|
// Returns an error if:
|
|
// - LOG_LEVEL contains an invalid value
|
|
// - LOG_OUTPUT contains an invalid value
|
|
// - LogDir or LogFileName is not set and file logging is enabled
|
|
func ConfigFromEnv() (*Config, error) {
|
|
logLevel, err := LogLevel(env.String("LOG_LEVEL", "info"))
|
|
if err != nil {
|
|
return nil, errors.Wrap(err, "LogLevel")
|
|
}
|
|
logOutput := env.String("LOG_OUTPUT", "console")
|
|
if logOutput != "both" && logOutput != "console" && logOutput != "file" {
|
|
return nil, errors.Errorf("Invalid LOG_OUTPUT: %s", logOutput)
|
|
}
|
|
cfg := &Config{
|
|
LogLevel: logLevel,
|
|
LogOutput: logOutput,
|
|
LogDir: env.String("LOG_DIR", ""),
|
|
LogFileName: env.String("LOG_FILE_NAME", ""),
|
|
LogAppend: env.Bool("LOG_APPEND", true),
|
|
}
|
|
if cfg.LogOutput != "console" {
|
|
if cfg.LogDir == "" {
|
|
return nil, errors.New("LOG_DIR not set but file logging enabled")
|
|
}
|
|
if cfg.LogFileName == "" {
|
|
return nil, errors.New("LOG_FILE_NAME not set but file logging enabled")
|
|
}
|
|
}
|
|
return cfg, nil
|
|
}
|