gocommon/log/hooks/file/config.go

77 lines
2.5 KiB
Go
Raw Normal View History

2022-11-26 20:45:32 +00:00
package file
import (
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"git.dev.m-and-m.ovh/mderasse/gocommon/convert"
2022-11-26 20:45:32 +00:00
"github.com/asaskevich/govalidator"
"github.com/juju/errors"
)
// ConfigStruct is the configuration for File Provider.
type ConfigStruct struct {
Filename string `yaml:"filename"`
Rotate bool `yaml:"rotate"`
RotateTime *string `yaml:"rotate_time"`
RotateMaxAge *string `yaml:"rotate_max_age"`
RotateMaxFile *int `yaml:"rotate_max_file"`
OutputFormat *string `yaml:"output_format"`
2022-11-26 20:45:32 +00:00
}
// IsValid will check that the File configuration is valid.
func (c *ConfigStruct) IsValid() error {
if c.Filename == "" {
return errors.NotValidf("Path is empty in File configuration")
} else if isValid, _ := govalidator.IsFilePath(c.Filename); !isValid {
return errors.NotValidf("Path is invalid in File configuration")
}
dir := filepath.Dir(c.Filename)
2022-11-26 20:45:32 +00:00
if _, err := os.Stat(dir); err != nil {
if errors.Is(err, fs.ErrPermission) {
return errors.NewForbidden(err, "Filename directory is not readeable in File configuration")
} else if errors.Is(err, fs.ErrNotExist) {
return errors.NewNotFound(err, "Filename directory does not exist in File configuration")
} else {
return errors.Trace(err)
}
2022-11-26 20:45:32 +00:00
}
if c.Rotate {
if c.RotateTime == nil || *c.RotateTime == "" {
return errors.NotValidf("rotate_time cannot be null or an empty string in File configuration")
} else if _, err := time.ParseDuration(*c.RotateTime); err != nil {
return errors.NewNotValid(err, "rotate_time contain an invalid duration in File configuration")
}
if c.RotateMaxFile != nil && *c.RotateMaxFile <= 0 {
return errors.NotValidf("rotate_max_file cannot be negative or 0 in File configuration")
}
if c.RotateMaxAge != nil && *c.RotateMaxAge == "" {
return errors.NotValidf("rotate_max_age cannot be an empty string in File configuration")
} else if c.RotateMaxAge != nil {
if _, err := time.ParseDuration(*c.RotateMaxAge); err != nil {
return errors.NewNotValid(err, "rotate_max_age contain an invalid duration in File configuration")
}
}
if c.RotateMaxFile != nil && c.RotateMaxAge != nil {
return errors.NotValidf("rotate_max_age and rotate_max_file cannot be defined at the same time in File configuration")
}
2022-11-26 20:45:32 +00:00
}
if c.OutputFormat != nil && !OutputFormat(*c.OutputFormat).IsValid() {
return errors.NotValidf("output_format is invalid in File configuration. (Possible Values:Allowed values: %s", strings.Join(convert.StringerSliceToStringSlice(GetListOutputFormat()), ", "))
}
return nil
2022-11-26 20:45:32 +00:00
}