103 lines
2.0 KiB
Go
103 lines
2.0 KiB
Go
package log
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
|
|
"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() (*logrus.Logger, error) {
|
|
|
|
// loading configuration
|
|
c, err := loadConfig()
|
|
if err != nil {
|
|
return nil, errors.Trace(err)
|
|
}
|
|
|
|
return initFromSource(c)
|
|
}
|
|
|
|
// InitLogFromCustomVaultSecret will initialize logger with a vault secret.
|
|
func InitLogFromCustomVaultSecret(secret string) (*logrus.Logger, error) {
|
|
|
|
c, err := loadConfigFromVault(secret)
|
|
if err != nil {
|
|
return nil, errors.Trace(err)
|
|
}
|
|
|
|
return initFromSource(c)
|
|
}
|
|
|
|
// InitLogFromCustomFile will initialize logger with a config file.
|
|
func InitLogFromCustomFile(path string) (*logrus.Logger, error) {
|
|
|
|
c, err := loadConfigFromFile(path)
|
|
if err != nil {
|
|
return nil, errors.Trace(err)
|
|
}
|
|
|
|
return initFromSource(c)
|
|
}
|
|
|
|
func initFromSource(c *ConfigStruct) (*logrus.Logger, error) {
|
|
err := c.applyEnv()
|
|
if err != nil {
|
|
return nil, errors.Trace(err)
|
|
}
|
|
|
|
c.applyDefault()
|
|
|
|
return InitLogFromCustomConfig(c)
|
|
}
|
|
|
|
// InitLogFromCustomConfig will initialize logger from a gaven config.
|
|
func InitLogFromCustomConfig(c *ConfigStruct) (*logrus.Logger, error) {
|
|
|
|
err := c.IsValid()
|
|
if err != nil {
|
|
return nil, errors.Trace(err)
|
|
}
|
|
|
|
level, err := logrus.ParseLevel(*c.Level)
|
|
if err != nil {
|
|
return nil, 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 nil, errors.Trace(err)
|
|
}
|
|
log.AddHook(hook)
|
|
case ProviderName_GELF:
|
|
hook, err := gelf.NewHook(c.GelfConfig)
|
|
if err != nil {
|
|
return nil, errors.Trace(err)
|
|
}
|
|
log.AddHook(hook)
|
|
case ProviderName_NONE:
|
|
fallthrough
|
|
default:
|
|
return nil, errors.BadRequestf("Provider is not handled.")
|
|
}
|
|
|
|
return log, nil
|
|
}
|