gocommon/log/log.go
Matthieu 'JP' DERASSE 5591da9c47
Some checks failed
continuous-integration/drone/push Build is failing
feat(log): Working on log library
2022-11-28 22:06:42 +00:00

107 lines
1.9 KiB
Go

package log
import (
"io"
"os"
"time"
"github.com/juju/errors"
"github.com/sirupsen/logrus"
"git.dev.m-and-m.ovh/mderasse/gocommon/log/hooks/file"
"git.dev.m-and-m.ovh/mderasse/gocommon/log/hooks/gelf"
)
// InitLog will try to initialize logger by trying to retrieve config from multiple source.
func InitLog() error {
// loading configuration
c, err := loadConfig()
if err != nil {
return errors.Trace(err)
}
return initFromSource(c)
}
// InitLogFromCustomVaultSecret will initialize logger with a vault secret.
func InitLogFromCustomVaultSecret(secret string) error {
c, err := loadConfigFromVault(secret)
if err != nil {
return errors.Trace(err)
}
return initFromSource(c)
}
// InitLogFromCustomFile will initialize logger with a config file.
func InitLogFromCustomFile(path string) error {
c, err := loadConfigFromFile(path)
if err != nil {
return errors.Trace(err)
}
return initFromSource(c)
}
func initFromSource(c *ConfigStruct) error {
err := c.applyEnv()
if err != nil {
return errors.Trace(err)
}
c.applyDefault()
return InitLogFromCustomConfig(c)
}
// InitLogFromCustomConfig will initialize logger from a gaven config.
func InitLogFromCustomConfig(c *ConfigStruct) error {
err := c.IsValid()
if err != nil {
return errors.Trace(err)
}
level, err := logrus.ParseLevel(*c.Level)
if err != nil {
return err
}
// init logger
log := logrus.New()
log.SetLevel(level)
if *c.EnableStdOut {
log.SetOutput(os.Stdout)
} else {
log.SetOutput(io.Discard)
}
switch *c.Provider {
case ProviderName_FILE:
hook, err := file.NewHook(c.FileConfig)
if err != nil {
return errors.Trace(err)
}
log.AddHook(hook)
case ProviderName_GELF:
hook, err := gelf.NewHook(c.GelfConfig)
if err != nil {
return errors.Trace(err)
}
log.AddHook(hook)
case ProviderName_NONE:
// Do Nothing
default:
}
for i := 0; i < 50; i++ {
log.Infof("Test %d", i)
time.Sleep(1 * time.Second)
}
return nil
}