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" ) // Init will try to initialize logger by trying to retrieve config from multiple source. func Init() (*logrus.Entry, error) { // loading configuration c, err := loadConfig() if err != nil { return nil, errors.Trace(err) } return initFromSource(c) } // InitFromCustomVaultSecret will initialize logger with a vault secret. func InitFromCustomVaultSecret(secret string) (*logrus.Entry, error) { c, err := loadConfigFromVault(secret) if err != nil { return nil, errors.Trace(err) } return initFromSource(c) } // InitFromCustomFile will initialize logger with a config file. func InitFromCustomFile(path string) (*logrus.Entry, error) { c, err := loadConfigFromFile(path) if err != nil { return nil, errors.Trace(err) } return initFromSource(c) } func initFromSource(c *ConfigStruct) (*logrus.Entry, error) { err := c.applyEnv() if err != nil { return nil, errors.Trace(err) } c.applyDefault() return InitFromCustomConfig(c) } // InitFromCustomConfig will initialize logger from a gaven config. func InitFromCustomConfig(c *ConfigStruct) (*logrus.Entry, error) { err := c.IsValid() if err != nil { return nil, errors.Trace(err) } level, err := logrus.ParseLevel(*c.Level) if err != nil { return nil, errors.Trace(err) } // init logger log := logrus.New() log.SetLevel(level) if *c.EnableStdOut { log.SetOutput(os.Stdout) } else { log.SetOutput(io.Discard) } for _, provider := range c.Providers { switch 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: // Do nothing, None can be use in case of StdOut Only. default: return nil, errors.BadRequestf("Provider is not handled.") } } return c.applyExtraFields(logrus.NewEntry(log)), nil } // applyExtraFileds will take a logrus.Entry and will add fields that are in the configuration. func (c *ConfigStruct) applyExtraFields(l *logrus.Entry) *logrus.Entry { return l.WithFields(c.ExtrasFields) }