updated hlog
This commit is contained in:
55
hlog/config.go
Normal file
55
hlog/config.go
Normal file
@@ -0,0 +1,55 @@
|
||||
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 // ENV LOG_LEVEL: Log level for the logger - trace, debug, info, warn, error, fatal, panic (default: info)
|
||||
LogOutput string // ENV LOG_OUTPUT: Output destination for logs - console, file, or both (default: console)
|
||||
LogDir string // ENV LOG_DIR: Directory path for log files (required when LOG_OUTPUT is "file" or "both")
|
||||
LogFileName string // ENV LOG_FILE_NAME: Name of the log file (required when LOG_OUTPUT is "file" or "both")
|
||||
LogAppend bool // ENV LOG_APPEND: 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
|
||||
}
|
||||
Reference in New Issue
Block a user