diff --git a/uchiwa/aggregate.go b/uchiwa/aggregate.go index 36b948f..d1f3462 100644 --- a/uchiwa/aggregate.go +++ b/uchiwa/aggregate.go @@ -3,20 +3,20 @@ package uchiwa import ( "fmt" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) // DeleteAggregate deletes a specific aggregate func (u *Uchiwa) DeleteAggregate(name, dc string) error { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } err = api.DeleteAggregate(name) if err != nil { - logger.Warning(err) + log.Warn(err) return err } @@ -27,13 +27,13 @@ func (u *Uchiwa) DeleteAggregate(name, dc string) error { func (u *Uchiwa) GetAggregate(name, dc string) (*map[string]interface{}, error) { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } aggregate, err := api.GetAggregate(name) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } @@ -44,13 +44,13 @@ func (u *Uchiwa) GetAggregate(name, dc string) (*map[string]interface{}, error) func (u *Uchiwa) GetAggregateChecks(name, dc string) (*[]interface{}, error) { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } checks, err := api.GetAggregateChecks(name) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } @@ -61,13 +61,13 @@ func (u *Uchiwa) GetAggregateChecks(name, dc string) (*[]interface{}, error) { func (u *Uchiwa) GetAggregateClients(name, dc string) (*[]interface{}, error) { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } clients, err := api.GetAggregateClients(name) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } @@ -78,13 +78,13 @@ func (u *Uchiwa) GetAggregateClients(name, dc string) (*[]interface{}, error) { func (u *Uchiwa) GetAggregateResults(name, severity, dc string) (*[]interface{}, error) { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } results, err := api.GetAggregateResults(name, severity) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } @@ -96,7 +96,9 @@ func (u *Uchiwa) findAggregate(name string) ([]interface{}, error) { for _, c := range u.Data.Aggregates { m, ok := c.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this check to an interface %+v", c) + log.WithFields(log.Fields{ + "interface": c, + }).Warn("Could not assert this check to an interface.") continue } if m["name"] == name { diff --git a/uchiwa/authentication/accessToken.go b/uchiwa/authentication/accessToken.go index 46419f6..32f3339 100644 --- a/uchiwa/authentication/accessToken.go +++ b/uchiwa/authentication/accessToken.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/dgrijalva/jwt-go" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) // TokenLocation represents a function that accepts a request as input and returns @@ -24,7 +24,7 @@ func accessTokenFromAuthHeader(r *http.Request) (string, error) { authorizationComponents := strings.Split(authorization, " ") if len(authorizationComponents) != 2 || strings.ToLower(authorizationComponents[0]) != "token" { - logger.Debug("Invalid authorization header. The format must be: token {token}") + log.Debug("Invalid authorization header. The format must be: token {token}") return "", errors.New("") } diff --git a/uchiwa/authentication/controllers.go b/uchiwa/authentication/controllers.go index 453b0f0..a84378c 100644 --- a/uchiwa/authentication/controllers.go +++ b/uchiwa/authentication/controllers.go @@ -7,8 +7,8 @@ import ( "github.com/gorilla/context" "github.com/sensu/uchiwa/uchiwa/audit" "github.com/sensu/uchiwa/uchiwa/helpers" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // New function initalizes and returns a Config struct @@ -33,7 +33,7 @@ func restrictedHandler(next http.Handler) http.Handler { // Verify the JWT token, err := verifyJWT(r) if err != nil { - logger.Debug("No JWT token provided") + log.Debug("No JWT token provided") } // Verify the access token if no JWT was provided @@ -43,7 +43,7 @@ func restrictedHandler(next http.Handler) http.Handler { // If no JWT or access token found if err != nil { - logger.Debug("No access token provided") + log.Debug("No access token provided") http.Error(w, "Request unauthorized", http.StatusUnauthorized) return } @@ -71,14 +71,18 @@ func (a *Config) Login() http.Handler { var data interface{} err := decoder.Decode(&data) if err != nil { - logger.Warningf("Could not decode the body: %s", err) + log.WithFields(log.Fields{ + "error": err, + }).Warn("Could not decode the body.") http.Error(w, "", http.StatusInternalServerError) return } m, ok := data.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert the body: %s", err) + log.WithFields(log.Fields{ + "error": err, + }).Warn("Could not assert the body.") http.Error(w, "", http.StatusInternalServerError) return } @@ -86,14 +90,14 @@ func (a *Config) Login() http.Handler { u := m["user"].(string) p := m["pass"].(string) if u == "" || p == "" { - logger.Info("Authentication failed: user and password must not be empty") + log.Info("Authentication failed: user and password must not be empty") http.Error(w, "", http.StatusUnauthorized) return } user, err := a.login(u, p) if err != nil { - logger.Info(err) + log.Info(err) // Output to audit log log := structs.AuditLog{Action: "loginfailure", Level: "default", Output: err.Error()} diff --git a/uchiwa/authentication/jwt.go b/uchiwa/authentication/jwt.go index 2b1fc2c..47c913a 100644 --- a/uchiwa/authentication/jwt.go +++ b/uchiwa/authentication/jwt.go @@ -10,8 +10,8 @@ import ( "github.com/dgrijalva/jwt-go" "github.com/gorilla/context" "github.com/mitchellh/mapstructure" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // JWTToken constant @@ -66,7 +66,9 @@ func GetToken(role *Role, username string) (string, error) { func generateKeyPair() *rsa.PrivateKey { keypair, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { - logger.Fatalf("Could not generate an RSA keypair: %s", err) + log.WithFields(log.Fields{ + "error": err, + }).Fatal("Could not generate an RSA keypair.") } return keypair @@ -75,7 +77,7 @@ func generateKeyPair() *rsa.PrivateKey { // generateToken generates a private and public RSA keys // in order to be used for the JWT signature func generateToken() (*rsa.PrivateKey, *rsa.PublicKey) { - logger.Debug("Generating new temporary RSA keys") + log.Debug("Generating new temporary RSA keys") privateKey := generateKeyPair() // Precompute some calculations privateKey.Precompute() @@ -92,7 +94,7 @@ func initToken(a structs.Auth) { privateKey, publicKey, err = loadToken(a) if err != nil { // At this point we need to generate temporary RSA keys - logger.Debug(err) + log.Debug(err) privateKey, publicKey = generateToken() } } @@ -100,7 +102,7 @@ func initToken(a structs.Auth) { // loadToken loads a private and public RSA keys from the filesystem // in order to be used for the JWT signature func loadToken(a structs.Auth) (*rsa.PrivateKey, *rsa.PublicKey, error) { - logger.Debug("Attempting to load the RSA keys from the filesystem") + log.Debug("Attempting to load the RSA keys from the filesystem") if a.PrivateKey == "" || a.PublicKey == "" { return nil, nil, errors.New("The paths to the private and public RSA keys were not provided") @@ -109,24 +111,32 @@ func loadToken(a structs.Auth) (*rsa.PrivateKey, *rsa.PublicKey, error) { // Read the files from the filesystem prv, err := ioutil.ReadFile(a.PrivateKey) if err != nil { - logger.Fatalf("Unable to open the private key file: %v", err) + log.WithFields(log.Fields{ + "error": err, + }).Fatal("Unable to open the private key file.") } pub, err := ioutil.ReadFile(a.PublicKey) if err != nil { - logger.Fatalf("Unable to open the public key file: %v", err) + log.WithFields(log.Fields{ + "error": err, + }).Fatal("Unable to open the public key file.") } // Parse the RSA keys privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(prv) if err != nil { - logger.Fatalf("Unable to parse the private key: %v", err) + log.WithFields(log.Fields{ + "error": err, + }).Fatal("Unable to parse the private key file.") } publicKey, err := jwt.ParseRSAPublicKeyFromPEM(pub) if err != nil { - logger.Fatalf("Unable to parse the public key: %v", err) + log.WithFields(log.Fields{ + "error": err, + }).Fatal("Unable to parse the public key.") } - logger.Info("Provided RSA keys successfully loaded") + log.Info("Provided RSA keys successfully loaded") return privateKey, publicKey, nil } @@ -139,7 +149,9 @@ func setJWTInContext(r *http.Request, token *jwt.Token) { func verifyJWT(r *http.Request) (*jwt.Token, error) { token, err := jwt.ParseFromRequest(r, func(t *jwt.Token) (interface{}, error) { if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok { - logger.Debugf("Unexpected signing method: %v", t.Header["alg"]) + log.WithFields(log.Fields{ + "method": t.Header["alg"], + }).Debug("Unexpected signing method.") return nil, errors.New("") } return publicKey, nil @@ -150,7 +162,7 @@ func verifyJWT(r *http.Request) (*jwt.Token, error) { } if !token.Valid { - logger.Debug("Invalid JWT") + log.Debug("Invalid JWT") return nil, errors.New("") } diff --git a/uchiwa/authorization/authorization.go b/uchiwa/authorization/authorization.go index c192200..2f792e4 100644 --- a/uchiwa/authorization/authorization.go +++ b/uchiwa/authorization/authorization.go @@ -4,7 +4,7 @@ import ( "net/http" "github.com/sensu/uchiwa/uchiwa/authentication" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) // Authorization contains the different methods used for authorizing @@ -44,13 +44,13 @@ func isReadOnly(r *http.Request) bool { token := authentication.GetJWTFromContext(r) if token == nil { // authentication is not enabled - logger.Debug("No JWT found in context") + log.Debug("No JWT found in context") return false } role, err := authentication.GetRoleFromToken(token) if err != nil { - logger.Debug("Invalid token: %s", err) + log.Debug("Invalid token: %s", err) return true } diff --git a/uchiwa/check.go b/uchiwa/check.go index aa9fd18..c303300 100644 --- a/uchiwa/check.go +++ b/uchiwa/check.go @@ -3,21 +3,21 @@ package uchiwa import ( "fmt" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // IssueCheckExecution sends a POST request to the /stashes endpoint in order to create a stash func (u *Uchiwa) IssueCheckExecution(data structs.CheckExecution) error { api, err := getAPI(u.Datacenters, data.Dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } _, err = api.IssueCheckExecution(data) if err != nil { - logger.Warning(err) + log.Warn(err) return err } @@ -29,7 +29,9 @@ func (u *Uchiwa) findCheck(name string) ([]interface{}, error) { for _, c := range u.Data.Checks { m, ok := c.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this check to an interface %+v", c) + log.WithFields(log.Fields{ + "interface": c, + }).Warn("Could not assert this check to an interface.") continue } if m["name"] == name { diff --git a/uchiwa/client.go b/uchiwa/client.go index ab23af0..cbec971 100644 --- a/uchiwa/client.go +++ b/uchiwa/client.go @@ -4,14 +4,16 @@ import ( "fmt" "github.com/sensu/uchiwa/uchiwa/helpers" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) func (u *Uchiwa) buildClientHistory(client, dc string, history []interface{}) []interface{} { for _, h := range history { m, ok := h.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this client history to an interface: %+v", h) + log.WithFields(log.Fields{ + "history": h, + }).Warn("Could not assert this client history to an interface.") continue } @@ -20,7 +22,9 @@ func (u *Uchiwa) buildClientHistory(client, dc string, history []interface{}) [] check, ok := m["last_result"].(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this check to a struct: %+v", m["last_result"]) + log.WithFields(log.Fields{ + "check": m["last_result"], + }).Warn("Could not assert this check to a struct.") continue } @@ -34,13 +38,13 @@ func (u *Uchiwa) buildClientHistory(client, dc string, history []interface{}) [] func (u *Uchiwa) DeleteClient(dc, name string) error { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } err = api.DeleteClient(name) if err != nil { - logger.Warning(err) + log.Warn(err) return err } @@ -52,7 +56,9 @@ func (u *Uchiwa) findClient(name string) ([]interface{}, error) { for _, c := range u.Data.Clients { m, ok := c.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this client to an interface %+v", c) + log.WithFields(log.Fields{ + "client": c, + }).Warn("Could not assert this client to an interface.") continue } if m["name"] == name { @@ -76,7 +82,9 @@ func (u *Uchiwa) findOutput(id *string, h map[string]interface{}, dc *string) st // does the dc match? m, ok := e.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this event to an interface %+v", e) + log.WithFields(log.Fields{ + "event": e, + }).Warn("Could not assert this event to an interface.") continue } if m["dc"] != *dc { @@ -86,7 +94,9 @@ func (u *Uchiwa) findOutput(id *string, h map[string]interface{}, dc *string) st // does the client match? c, ok := m["client"].(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this client to an interface: %+v", c) + log.WithFields(log.Fields{ + "client": c, + }).Warn("Could not assert this client to an interface.") continue } @@ -97,7 +107,9 @@ func (u *Uchiwa) findOutput(id *string, h map[string]interface{}, dc *string) st // does the check match? k := m["check"].(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this check to an interface: %+v", k) + log.WithFields(log.Fields{ + "check": k, + }).Warn("Could not assert this check to an interface.") continue } if k["name"] != h["check"] { @@ -113,13 +125,13 @@ func (u *Uchiwa) findOutput(id *string, h map[string]interface{}, dc *string) st func (u *Uchiwa) GetClient(dc, name string) (map[string]interface{}, error) { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } client, err := api.GetClient(name) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } @@ -138,13 +150,13 @@ func (u *Uchiwa) GetClient(dc, name string) (map[string]interface{}, error) { func (u *Uchiwa) GetClientHistory(dc, name string) ([]interface{}, error) { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } h, err := api.GetClientHistory(name) if err != nil { - logger.Warning(err) + log.Warn(err) return nil, err } diff --git a/uchiwa/config/config.go b/uchiwa/config/config.go index 6956359..e1e193a 100644 --- a/uchiwa/config/config.go +++ b/uchiwa/config/config.go @@ -10,7 +10,7 @@ import ( "github.com/palourde/mergo" "github.com/sensu/uchiwa/uchiwa/authentication" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) var ( @@ -57,16 +57,16 @@ func Load(file, directories string) *Config { var err error Private, err = loadFile(file) if err != nil { - logger.Fatal(err) + log.Fatal(err) } // Apply default configs to the configuration file if err := mergo.Merge(Private, defaultConfig); err != nil { - logger.Fatal(err) + log.Fatal(err) } for i := range Private.Sensu { if err := mergo.Merge(&Private.Sensu[i], defaultSensuConfig); err != nil { - logger.Fatal(err) + log.Fatal(err) } } @@ -74,7 +74,7 @@ func Load(file, directories string) *Config { configDir := loadDirectories(directories) // Overwrite the file config with the configs from the directories if err := mergo.MergeWithOverwrite(Private, configDir); err != nil { - logger.Fatal(err) + log.Fatal(err) } } @@ -85,7 +85,7 @@ func Load(file, directories string) *Config { Private.Uchiwa = *Private.Dashboard // Apply the default config to the dashboard attribute if err := mergo.Merge(Private, defaultConfig); err != nil { - logger.Fatal(err) + log.Fatal(err) } } @@ -103,7 +103,7 @@ func loadDirectories(path string) *Config { // Find all JSON files in the specified directories files, err := filepath.Glob(filepath.Join(directory, "*.json")) if err != nil { - logger.Warning(err) + log.Warn(err) continue } @@ -118,13 +118,13 @@ func loadDirectories(path string) *Config { // Load the config from the file c, err := loadFile(file) if err != nil { - logger.Warning(err) + log.Warn(err) continue } // Apply this configuration to the existing one if err := mergo.MergeWithOverwrite(conf, c); err != nil { - logger.Warning(err) + log.Warn(err) continue } } @@ -132,7 +132,7 @@ func loadDirectories(path string) *Config { // Apply the default config to the Sensu APIs for i := range conf.Sensu { if err := mergo.Merge(&conf.Sensu[i], defaultSensuConfig); err != nil { - logger.Fatal(err) + log.Fatal(err) } } @@ -141,7 +141,9 @@ func loadDirectories(path string) *Config { // loadFile loads a Config struct from a configuration file func loadFile(path string) (*Config, error) { - logger.Warningf("Loading the configuration file %s", path) + log.WithFields(log.Fields{ + "path": path, + }).Warn("Loading the configuration file.") c := new(Config) file, err := os.Open(path) @@ -164,7 +166,9 @@ func initSensu(apis []SensuConfig) []SensuConfig { for i, api := range apis { // Set a datacenter name if missing if api.Name == "" { - logger.Warningf("Sensu API %s has no name property, make sure to set it in your configuration. Generating a temporary one...", api.URL) + log.WithFields(log.Fields{ + "api": api.URL, + }).Warn("The Sensu API shown has no name property, make sure to set it in your configuration. Generating a temporary one...") apis[i].Name = fmt.Sprintf("sensu-%v", rand.Intn(100)) } @@ -174,7 +178,9 @@ func initSensu(apis []SensuConfig) []SensuConfig { // Make sure the host is not empty if api.Host == "" { - logger.Fatalf("Sensu API %q Host is missing", api.Name) + log.WithFields(log.Fields{ + "api": api.Name, + }).Fatal("The Sensu API shown has no host property.") } // Determine the protocol to use @@ -219,7 +225,7 @@ func initUchiwa(global GlobalConfig) GlobalConfig { } else if global.Db.Driver != "" && global.Db.Scheme != "" { global.Auth.Driver = "sql" } else if len(global.Users) != 0 { - logger.Debug("Loading multiple users from the config") + log.Debug("Loading multiple users from the config") global.Auth.Driver = "simple" for i := range global.Users { @@ -232,15 +238,25 @@ func initUchiwa(global GlobalConfig) GlobalConfig { authentication.Roles = append(authentication.Roles, global.Users[i].Role) } } else if global.User != "" && global.Pass != "" { - logger.Debug("Loading single user from the config") + log.Debug("Loading single user from the config") global.Auth.Driver = "simple" // Support multiple users global.Users = append(global.Users, authentication.User{Username: global.User, Password: global.Pass, FullName: global.User}) } - // Set the logger level - logger.SetLogLevel(global.LogLevel) + // Set the log level + switch global.LogLevel { + case "debug": log.SetLevel(log.DebugLevel) + case "info": log.SetLevel(log.InfoLevel) + case "warn": log.SetLevel(log.WarnLevel) + case "error": log.SetLevel(log.ErrorLevel) + case "panic": log.SetLevel(log.PanicLevel) + default: log.SetLevel(log.InfoLevel) + } + + // Set stdout as default log output + log.SetOutput(os.Stdout) // Set the refresh rate for frontend global.UsersOptions.Refresh = global.Refresh * 1000 diff --git a/uchiwa/daemon/clients.go b/uchiwa/daemon/clients.go index 18576c5..ce416f8 100644 --- a/uchiwa/daemon/clients.go +++ b/uchiwa/daemon/clients.go @@ -5,8 +5,8 @@ import ( "github.com/mitchellh/mapstructure" "github.com/sensu/uchiwa/uchiwa/helpers" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // buildClients constructs clients objects for frontend consumption @@ -47,7 +47,9 @@ func findClientEvents(client map[string]interface{}, events *[]interface{}) map[ eventMap, ok := e.(map[string]interface{}) if !ok { - logger.Warningf("Could not convert the event to a map: %+v", eventMap) + log.WithFields(log.Fields{ + "event": e, + }).Warn("Could not convert the event to a map.") continue } @@ -63,7 +65,9 @@ func findClientEvents(client map[string]interface{}, events *[]interface{}) map[ clientMap, ok := eventMap["client"].(map[string]interface{}) if !ok { - logger.Warningf("Could not convert the event's client to a map: %+v", eventMap) + log.WithFields(log.Fields{ + "client": eventMap["client"], + }).Warn("Could not convert the event's client to a map.") continue } @@ -76,7 +80,9 @@ func findClientEvents(client map[string]interface{}, events *[]interface{}) map[ var check structs.GenericCheck err := mapstructure.Decode(eventMap["check"], &check) if err != nil { - logger.Warningf("Could not convert the event's check to a generic check structure: %s", err) + log.WithFields(log.Fields{ + "err": err, + }).Warn("Could not convert the event's check to a generic check structure.") continue } diff --git a/uchiwa/daemon/daemon.go b/uchiwa/daemon/daemon.go index e321c70..6d772d9 100644 --- a/uchiwa/daemon/daemon.go +++ b/uchiwa/daemon/daemon.go @@ -3,9 +3,9 @@ package daemon import ( "time" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/sensu" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) const datacenterErrorString = "Connection error. Is the Sensu API running?" @@ -31,9 +31,9 @@ func (d *Daemon) Start(interval int, data chan *structs.Data) { select { case data <- d.Data: - logger.Trace("Sending initial results on the 'data' channel") + log.Debug("Sending initial results on the 'data' channel") default: - logger.Trace("Could not send initial results on the 'data' channel") + log.Debug("Could not send initial results on the 'data' channel") } // fetch new data every interval @@ -46,9 +46,9 @@ func (d *Daemon) Start(interval int, data chan *structs.Data) { // send the result over the data channel select { case data <- d.Data: - logger.Trace("Sending results on the 'data' channel") + log.Debug("Sending results on the 'data' channel") default: - logger.Trace("Could not send results on the 'data' channel") + log.Debug("Could not send results on the 'data' channel") } } } @@ -71,7 +71,9 @@ func (d *Daemon) fetchData() { d.Data.Health.Sensu = make(map[string]structs.SensuHealth, len(*d.Datacenters)) for _, datacenter := range *d.Datacenters { - logger.Infof("Updating the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Info("Updating the datacenter.") // set default health status d.Data.Health.Sensu[datacenter.Name] = structs.SensuHealth{Output: datacenterErrorString, Status: 2} @@ -80,37 +82,51 @@ func (d *Daemon) fetchData() { // fetch sensu data from the datacenter stashes, err := datacenter.GetStashes() if err != nil { - logger.Warningf("Connection failed to the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Connection failed to the datacenter.") continue } silenced, err := datacenter.GetSilenced() if err != nil { - logger.Warningf("Impossible to retrieve silenced entries from the "+ - "datacenter %s. Silencing might not be possible, please update Sensu", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Impossible to retrieve silenced entries from the following datacenter. " + + "Silencing might not be possible, please update Sensu") } checks, err := datacenter.GetChecks() if err != nil { - logger.Warningf("Connection failed to the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Connection failed to the datacenter.") continue } clients, err := datacenter.GetClients() if err != nil { - logger.Warningf("Connection failed to the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Connection failed to the datacenter.") continue } events, err := datacenter.GetEvents() if err != nil { - logger.Warningf("Connection failed to the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Connection failed to the datacenter.") continue } info, err := datacenter.GetInfo() if err != nil { - logger.Warningf("Connection failed to the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Connection failed to the datacenter.") continue } aggregates, err := datacenter.GetAggregates() if err != nil { - logger.Warningf("Connection failed to the datacenter %s", datacenter.Name) + log.WithFields(log.Fields{ + "datacenter": datacenter.Name, + }).Warn("Connection failed to the datacenter.") continue } @@ -178,7 +194,10 @@ func getEnterpriseMetrics(datacenter SensuDatacenter, metrics *structs.SERawMetr for _, metric := range metricsEndpoints { m[metric], err = datacenter.Metric(metric) if err != nil { - logger.Debugf("Could not retrieve the %s enterprise metrics. %s", metric, datacenter.GetName()) + log.WithFields(log.Fields{ + "datacenter": datacenter.GetName(), + "metric": metric, + }).Debug("Could not retrieve the metric indicated for the following datacenter.") m[metric] = &structs.SERawMetric{} } } diff --git a/uchiwa/daemon/events.go b/uchiwa/daemon/events.go index 2906e94..602d776 100644 --- a/uchiwa/daemon/events.go +++ b/uchiwa/daemon/events.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/sensu/uchiwa/uchiwa/helpers" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) // BuildEvents constructs events objects for frontend consumption @@ -15,33 +15,43 @@ func (d *Daemon) buildEvents() { // get client name clientMap, ok := m["client"].(map[string]interface{}) if !ok { - logger.Warningf("Could not assert event's client interface from %+v", clientMap) + log.WithFields(log.Fields{ + "client": m["client"], + }).Warn("Could not assert event's client interface.") continue } client, ok := clientMap["name"].(string) if !ok { - logger.Warningf("Could not assert event's client name from %+v", clientMap) + log.WithFields(log.Fields{ + "name": clientMap["name"], + }).Warn("Could not assert event's client name from client map.") continue } // get check name checkMap, ok := m["check"].(map[string]interface{}) if !ok { - logger.Warningf("Could not assert event's check interface from %+v", checkMap) + log.WithFields(log.Fields{ + "check": m["check"], + }).Warn("Could not assert event's check from client map.") continue } check, ok := checkMap["name"].(string) if !ok { - logger.Warningf("Could not assert event's check name from %+v", checkMap) + log.WithFields(log.Fields{ + "name": checkMap["name"], + }).Warn("Could not assert event's check name from check map.") continue } // get dc name dc, ok := m["dc"].(string) if !ok { - logger.Warningf("Could not assert event's datacenter name from %+v", m) + log.WithFields(log.Fields{ + "name": m["dc"], + }).Warn("Could not assert event's datacenter name from check map.") continue } diff --git a/uchiwa/daemon/helpers.go b/uchiwa/daemon/helpers.go index e4bbf7d..9a78e52 100644 --- a/uchiwa/daemon/helpers.go +++ b/uchiwa/daemon/helpers.go @@ -4,21 +4,25 @@ import ( "errors" "fmt" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/sensu" + log "github.com/Sirupsen/logrus" ) // FindDcFromInterface ... func FindDcFromInterface(data interface{}, datacenters *[]sensu.Sensu) (*sensu.Sensu, map[string]interface{}, error) { m, ok := data.(map[string]interface{}) if !ok { - logger.Warningf("Type assertion failed. Could not assert the given interface into a map: %+v", data) + log.WithFields(log.Fields{ + "interface": data, + }).Warn("Type assertion failed. Could not assert the given interface into a map.") return nil, nil, errors.New("Could not determine the datacenter.") } id := m["dc"].(string) if id == "" { - logger.Warningf("The received interface does not contain any datacenter information: ", data) + log.WithFields(log.Fields{ + "interface": data, + }).Warn("The received interface does not contain any datacenter information.") return nil, nil, errors.New("Could not determine the datacenter.") } @@ -28,7 +32,10 @@ func FindDcFromInterface(data interface{}, datacenters *[]sensu.Sensu) (*sensu.S } } - logger.Warningf("Could not find the datacenter %s into %+v: ", id, data) + log.WithFields(log.Fields{ + "interface": data, + "id": id, + }).Warn("Could not find the datacenter.") return nil, nil, fmt.Errorf("Could not find the datacenter %s", id) } @@ -65,7 +72,9 @@ func setID(elements []interface{}, separator string) { func setDc(v interface{}, dc string) { m, ok := v.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert interface: %+v", v) + log.WithFields(log.Fields{ + "interface": v, + }).Warn("Could not assert interface.") } else { m["dc"] = dc } diff --git a/uchiwa/daemon/subscriptions.go b/uchiwa/daemon/subscriptions.go index 308d232..00d02b2 100644 --- a/uchiwa/daemon/subscriptions.go +++ b/uchiwa/daemon/subscriptions.go @@ -4,8 +4,8 @@ import ( "strings" "github.com/mitchellh/mapstructure" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // BuildSubscriptions builds a slice of every client subscriptions @@ -14,7 +14,7 @@ func (d *Daemon) BuildSubscriptions() { var generic structs.GenericClient err := mapstructure.Decode(client, &generic) if err != nil { - logger.Debug("%s", err) + log.Debug("%s", err) continue } diff --git a/uchiwa/event.go b/uchiwa/event.go index 3805d36..f077d71 100644 --- a/uchiwa/event.go +++ b/uchiwa/event.go @@ -1,19 +1,19 @@ package uchiwa -import "github.com/sensu/uchiwa/uchiwa/logger" +import log "github.com/Sirupsen/logrus" // ResolveEvent sends a DELETE request in order to // resolve an event for a given check on a given client func (u *Uchiwa) ResolveEvent(check, client, dc string) error { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } err = api.DeleteEvent(check, client) if err != nil { - logger.Warning(err) + log.Warn(err) return err } diff --git a/uchiwa/helpers.go b/uchiwa/helpers.go index 7e809bb..9ddc864 100644 --- a/uchiwa/helpers.go +++ b/uchiwa/helpers.go @@ -4,8 +4,8 @@ import ( "errors" "fmt" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/sensu" + log "github.com/Sirupsen/logrus" ) func getAPI(datacenters *[]sensu.Sensu, name string) (*sensu.Sensu, error) { @@ -30,7 +30,9 @@ func findModel(id string, dc string, checks []interface{}) map[string]interface{ for _, k := range checks { m, ok := k.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert check interface %+v", k) + log.WithFields(log.Fields{ + "check": k, + }).Warn("Could not assert check interface.") continue } if m["name"] == id && m["dc"] == dc { diff --git a/uchiwa/helpers/helpers.go b/uchiwa/helpers/helpers.go index 57e2d49..2694264 100644 --- a/uchiwa/helpers/helpers.go +++ b/uchiwa/helpers/helpers.go @@ -7,8 +7,8 @@ import ( "net" "net/http" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // BuildClientsMetrics builds the metrics for the events @@ -29,7 +29,9 @@ func BuildClientsMetrics(clients *[]interface{}) *structs.StatusMetrics { status, ok := client["status"].(int) if !ok { - logger.Warningf("Could not assert the status to an int: %+v", client["status"]) + log.WithFields(log.Fields{ + "status": client["status"], + }).Warn("Could not assert the status to an int.") continue } @@ -68,13 +70,17 @@ func BuildEventsMetrics(events *[]interface{}) *structs.StatusMetrics { check, ok := event["check"].(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this check to an interface: %+v", event["check"]) + log.WithFields(log.Fields{ + "check": event["check"], + }).Warn("Could not assert this check to an interface.") continue } status, ok := check["status"].(float64) if !ok { - logger.Warningf("Could not assert this status to a flot64: %+v", check["status"]) + log.WithFields(log.Fields{ + "status": check["status"], + }).Warn("Could not assert this status to a float64.") continue } @@ -94,14 +100,16 @@ func BuildEventsMetrics(events *[]interface{}) *structs.StatusMetrics { // GetBoolFromInterface ... func GetBoolFromInterface(i interface{}) (bool, error) { if i == nil { - logger.Debug("The interface is nil") + log.Debug("The interface is nil") return false, errors.New("The interface is nil") } b, ok := i.(bool) if !ok { - logger.Debugf("Could not assert to a boolean the interface: %+v", i) - return false, errors.New("Could not assert to a boolean the interface") + log.WithFields(log.Fields{ + "interface": i, + }).Debug("Could not assert interface to a boolean.") + return false, errors.New("Could not assert interface to a boolean.") } return b, nil @@ -183,7 +191,9 @@ func GetMapFromBytes(bytes []byte) (map[string]interface{}, error) { func GetMapFromInterface(i interface{}) map[string]interface{} { m, ok := i.(map[string]interface{}) if !ok { - logger.Debugf("Could not assert to a map the interface: %+v", i) + log.WithFields(log.Fields{ + "interface": i, + }).Debug("Could not assert interface to a map.") return nil } @@ -225,7 +235,9 @@ func IsCheckSilenced(check map[string]interface{}, client, dc string, silenced [ for _, silence := range silenced { m, ok := silence.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this silence entry to a map: %+v", silence) + log.WithFields(log.Fields{ + "silence": silence, + }).Warn("Could not assert this silence entry to a map.") continue } diff --git a/uchiwa/logger/logger.go b/uchiwa/logger/logger.go deleted file mode 100644 index cb427ca..0000000 --- a/uchiwa/logger/logger.go +++ /dev/null @@ -1,176 +0,0 @@ -package logger - -import ( - "encoding/json" - "fmt" - "os" - "runtime" - "strings" - "time" -) - -// Logging Levels -const ( - FATAL int = iota - WARN - INFO - DEBUG - TRACE -) - -var configuredLevel int - -var levels = []string{"FATAL", "WARN", "INFO", "DEBUG", "TRACE"} - -// Logger stuct contains the log details -type Logger struct { - Timestamp time.Time `json:"timestamp"` - Level *string `json:"level"` - Src *Source `json:"src,omitempty"` - Message *string `json:"message"` -} - -// Source struct contains the source details -type Source struct { - Func string `json:"func,omitempty"` - Line int `json:"line,omitempty"` -} - -var log = new(Logger) - -func init() { - configuredLevel = INFO -} - -func (l *Logger) caller() { - var ok bool - var pc uintptr - var src Source - - pc, _, src.Line, ok = runtime.Caller(3) - if !ok { - src.Func = "???" - src.Line = 0 - } else { - src.Func = runtime.FuncForPC(pc).Name() - } - - l.Src = &src -} - -func (l *Logger) message(format string, args []interface{}) *string { - m := fmt.Sprintf(format, args...) - return &m -} - -func (l *Logger) now() { - l.Timestamp = time.Now() -} - -func (l *Logger) print(level string, format string, args ...interface{}) { - l.now() - l.Message = l.message(format, args) - l.Level = &level - - // Are we priting logs for this level? - if isDisabledFor(level) { - return - } - - // Do we need to add additional information to the message? - if configuredLevel >= DEBUG { - l.caller() - } - - data, err := json.Marshal(l) - if err != nil { - fmt.Println(err) - return - } - fmt.Println(string(data)) -} - -// Debug function logs a message using DEBUG as log level if DEBUG environment variable is enabled -func Debug(args ...interface{}) { - s := fmt.Sprint(args...) - log.print("debug", "%s", s) -} - -// Debugf function logs a message with arguments using DEBUG as log level if DEBUG environment variable is enabled -func Debugf(format string, args ...interface{}) { - s := fmt.Sprintf(format, args...) - log.print("debug", s) -} - -// Fatal function logs a message using FATAL as log level followed by a call to os.Exit(1) -func Fatal(args ...interface{}) { - s := fmt.Sprint(args...) - log.print("fatal", "%s", s) - os.Exit(1) -} - -// Fatalf function logs a message with arguments using FATAL as log level followed by a call to os.Exit(1) -func Fatalf(format string, args ...interface{}) { - s := fmt.Sprintf(format, args...) - log.print("fatal", s) - os.Exit(1) -} - -// Info function logs a message using INFO as log level -func Info(args ...interface{}) { - s := fmt.Sprint(args...) - log.print("info", "%s", s) -} - -// Infof function logs a message with arguments using INFO as log level -func Infof(format string, args ...interface{}) { - s := fmt.Sprintf(format, args...) - log.print("info", s) -} - -// Trace function logs a message using TRACE as log level -func Trace(args ...interface{}) { - s := fmt.Sprint(args...) - log.print("trace", "%s", s) -} - -// Tracef function logs a message with arguments using TRACE as log level -func Tracef(format string, args ...interface{}) { - s := fmt.Sprintf(format, args...) - log.print("trace", s) -} - -// Warning function logs a message using WARNING as log level -func Warning(args ...interface{}) { - s := fmt.Sprint(args...) - log.print("warn", "%s", s) -} - -// Warningf function logs a message with arguments using WARNING as log level -func Warningf(format string, args ...interface{}) { - s := fmt.Sprintf(format, args...) - log.print("warn", s) -} - -// getLevelInt returns the integer representation of a logging level -func getLevelInt(level string) int { - for i, name := range levels { - if strings.EqualFold(name, level) { - return i - } - } - // Return info by default - return INFO -} - -// isDisabledFor returns true if logging is disabled for the provided level -func isDisabledFor(level string) bool { - levelInt := getLevelInt(level) - - return levelInt > configuredLevel -} - -// SetLogLevel ... -func SetLogLevel(level string) { - configuredLevel = getLevelInt(level) -} diff --git a/uchiwa/logger/logger_test.go b/uchiwa/logger/logger_test.go deleted file mode 100644 index dd00406..0000000 --- a/uchiwa/logger/logger_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package logger - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetLevelInt(t *testing.T) { - integer := getLevelInt("Trace") - assert.Equal(t, TRACE, integer) - - integer = getLevelInt("DEBUG") - assert.Equal(t, DEBUG, integer) - - integer = getLevelInt("info") - assert.Equal(t, INFO, integer) - - integer = getLevelInt("warn") - assert.Equal(t, WARN, integer) - - integer = getLevelInt("fatal") - assert.Equal(t, FATAL, integer) - - integer = getLevelInt("none") - assert.Equal(t, INFO, integer) -} - -func TestIsDisabledFor(t *testing.T) { - configuredLevel = TRACE - - enabled := isDisabledFor("trace") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("debug") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("info") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("warn") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("fatal") - assert.Equal(t, false, enabled) - - configuredLevel = DEBUG - - enabled = isDisabledFor("trace") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("debug") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("info") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("warn") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("fatal") - assert.Equal(t, false, enabled) - - configuredLevel = INFO - - enabled = isDisabledFor("trace") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("debug") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("info") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("warn") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("fatal") - assert.Equal(t, false, enabled) - - configuredLevel = WARN - - enabled = isDisabledFor("trace") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("debug") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("info") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("warn") - assert.Equal(t, false, enabled) - enabled = isDisabledFor("fatal") - assert.Equal(t, false, enabled) - - configuredLevel = FATAL - - enabled = isDisabledFor("trace") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("debug") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("info") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("warn") - assert.Equal(t, true, enabled) - enabled = isDisabledFor("fatal") - assert.Equal(t, false, enabled) -} diff --git a/uchiwa/main.go b/uchiwa/main.go index eeac416..061be5e 100644 --- a/uchiwa/main.go +++ b/uchiwa/main.go @@ -6,9 +6,9 @@ import ( "github.com/sensu/uchiwa/uchiwa/config" "github.com/sensu/uchiwa/uchiwa/daemon" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/sensu" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // Uchiwa structure is used to manage Uchiwa @@ -85,7 +85,7 @@ func (u *Uchiwa) listener(interval int, data chan *structs.Data) { for { select { case result := <-data: - logger.Trace("Received results on the 'data' channel") + log.Debug("Received results on the 'data' channel") u.Mu.Lock() u.Data = result diff --git a/uchiwa/results.go b/uchiwa/results.go index de2f12b..4b5a9f3 100644 --- a/uchiwa/results.go +++ b/uchiwa/results.go @@ -1,19 +1,19 @@ package uchiwa -import "github.com/sensu/uchiwa/uchiwa/logger" +import log "github.com/Sirupsen/logrus" // DeleteCheckResult sends a DELETE request in order to // remove the result for a given check on a given client func (u *Uchiwa) DeleteCheckResult(check, client, dc string) error { api, err := getAPI(u.Datacenters, dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } err = api.DeleteCheckResult(check, client) if err != nil { - logger.Warning(err) + log.Warn(err) return err } diff --git a/uchiwa/sensu/loadbalancing.go b/uchiwa/sensu/loadbalancing.go index aabf467..151a2ef 100644 --- a/uchiwa/sensu/loadbalancing.go +++ b/uchiwa/sensu/loadbalancing.go @@ -6,7 +6,7 @@ import ( "net/http" "time" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) // These are the methods directly used by the public methods of the sensu @@ -17,12 +17,19 @@ func (s *Sensu) delete(endpoint string) error { var err error for i := 0; i < len(apis); i++ { - logger.Infof("DELETE %s/%s", s.APIs[i].URL, endpoint) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + }).Debug("DELETE operation.") err = apis[i].delete(endpoint) if err == nil { return err } - logger.Warningf("DELETE %s/%s returned: %v", s.APIs[i].URL, endpoint, err) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + "error": err, + }).Warn("DELETE operation returned error.") } return err @@ -32,12 +39,19 @@ func (s *Sensu) getBytes(endpoint string) ([]byte, *http.Response, error) { apis := shuffle(s.APIs) for i := 0; i < len(apis); i++ { - logger.Debugf("GET %s/%s", s.APIs[i].URL, endpoint) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + }).Debug("GET operation.") bytes, res, err := apis[i].getBytes(endpoint) if err == nil { return bytes, res, err } - logger.Warningf("GET %s/%s returned: %v", s.APIs[i].URL, endpoint, err) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + "error": err, + }).Warn("GET operation returned error.") } return nil, nil, errors.New("") @@ -47,12 +61,19 @@ func (s *Sensu) getSlice(endpoint string, limit int) ([]interface{}, error) { apis := shuffle(s.APIs) for i := 0; i < len(apis); i++ { - logger.Debugf("GET %s/%s", s.APIs[i].URL, endpoint) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + }).Debug("GET operation.") slice, err := apis[i].getSlice(endpoint, limit) if err == nil { return slice, err } - logger.Warningf("GET %s/%s returned: %v", s.APIs[i].URL, endpoint, err) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + "error": err, + }).Warn("GET operation returned error.") } return nil, errors.New("") @@ -62,12 +83,19 @@ func (s *Sensu) getMap(endpoint string) (map[string]interface{}, error) { apis := shuffle(s.APIs) for i := 0; i < len(apis); i++ { - logger.Debugf("GET %s/%s", s.APIs[i].URL, endpoint) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + }).Debug("GET operation.") m, err := apis[i].getMap(endpoint) if err == nil { return m, err } - logger.Warningf("GET %s/%s returned: %v", s.APIs[i].URL, endpoint, err) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + "error": err, + }).Warn("GET operation returned error.") } return nil, errors.New("") @@ -77,12 +105,19 @@ func (s *Sensu) postPayload(endpoint string, payload string) (map[string]interfa apis := shuffle(s.APIs) for i := 0; i < len(apis); i++ { - logger.Debugf("POST %s/%s", s.APIs[i].URL, endpoint) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + }).Debug("POST operation.") m, err := apis[i].postPayload(endpoint, payload) if err == nil { return m, err } - logger.Warningf("POST %s/%s returned: %v", s.APIs[i].URL, endpoint, err) + log.WithFields(log.Fields{ + "url": s.APIs[i].URL, + "endpoint": endpoint, + "error": err, + }).Warn("POST operation returned error.") } return nil, errors.New("") diff --git a/uchiwa/sensu/methods.go b/uchiwa/sensu/methods.go index 1cda32f..3a09964 100644 --- a/uchiwa/sensu/methods.go +++ b/uchiwa/sensu/methods.go @@ -9,8 +9,8 @@ import ( "strings" "github.com/sensu/uchiwa/uchiwa/helpers" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // These are the methods of the API struct that interface the more basic @@ -54,7 +54,7 @@ func (api *API) getSlice(endpoint string, limit int) ([]interface{}, error) { err = json.Unmarshal([]byte(res.Header.Get("X-Pagination")), &xPagination) if err != nil { - logger.Warning(err) + log.Warn(err) } for len(list) < xPagination.Total { @@ -74,7 +74,9 @@ func (api *API) getSlice(endpoint string, limit int) ([]interface{}, error) { } if len(partialList) == 0 { - logger.Debugf("No additional elements found, exiting pagination for %s endpoint", endpoint) + log.WithFields(log.Fields{ + "endpoint": endpoint, + }).Debug("No additional elements found, exiting pagination for endpoint.") break } diff --git a/uchiwa/server.go b/uchiwa/server.go index 4334c60..ad2d9ec 100644 --- a/uchiwa/server.go +++ b/uchiwa/server.go @@ -10,8 +10,8 @@ import ( "github.com/sensu/uchiwa/uchiwa/authentication" "github.com/sensu/uchiwa/uchiwa/authorization" "github.com/sensu/uchiwa/uchiwa/filters" - "github.com/sensu/uchiwa/uchiwa/logger" "github.com/sensu/uchiwa/uchiwa/structs" + log "github.com/Sirupsen/logrus" ) // Authorization contains the available authorization methods @@ -880,7 +880,10 @@ func (u *Uchiwa) stashHandler(w http.ResponseWriter, r *http.Request) { err := u.DeleteStash(dc, path) if err != nil { - logger.Warningf("Could not delete the stash '%s': %s", path, err) + log.WithFields(log.Fields{ + "path": path, + "error": err, + }).Warn("Could not delete the stash.") http.Error(w, "Could not create the stash", http.StatusNotFound) return } @@ -1119,11 +1122,13 @@ func (u *Uchiwa) WebServer(publicPath *string, auth authentication.Config) { http.Handle("/login", auth.Login()) listen := fmt.Sprintf("%s:%d", u.Config.Uchiwa.Host, u.Config.Uchiwa.Port) - logger.Warningf("Uchiwa is now listening on %s", listen) + log.WithFields(log.Fields{ + "address": listen, + }).Warn("Uchiwa is now listening.") if u.Config.Uchiwa.SSL.CertFile != "" && u.Config.Uchiwa.SSL.KeyFile != "" { - logger.Fatal(http.ListenAndServeTLS(listen, u.Config.Uchiwa.SSL.CertFile, u.Config.Uchiwa.SSL.KeyFile, nil)) + log.Fatal(http.ListenAndServeTLS(listen, u.Config.Uchiwa.SSL.CertFile, u.Config.Uchiwa.SSL.KeyFile, nil)) } - logger.Fatal(http.ListenAndServe(listen, nil)) + log.Fatal(http.ListenAndServe(listen, nil)) } diff --git a/uchiwa/silenced.go b/uchiwa/silenced.go index 4b404bc..3757990 100644 --- a/uchiwa/silenced.go +++ b/uchiwa/silenced.go @@ -1,6 +1,6 @@ package uchiwa -import "github.com/sensu/uchiwa/uchiwa/logger" +import log "github.com/Sirupsen/logrus" type silence struct { ID string `json:"id"` @@ -17,13 +17,13 @@ type silence struct { func (u *Uchiwa) ClearSilenced(data silence) error { api, err := getAPI(u.Datacenters, data.Dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } _, err = api.ClearSilenced(data) if err != nil { - logger.Warning(err) + log.Warn(err) return err } @@ -34,13 +34,13 @@ func (u *Uchiwa) ClearSilenced(data silence) error { func (u *Uchiwa) PostSilence(data silence) error { api, err := getAPI(u.Datacenters, data.Dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } _, err = api.Silence(data) if err != nil { - logger.Warning(err) + log.Warn(err) return err } diff --git a/uchiwa/stash.go b/uchiwa/stash.go index fdb4beb..d0bf42c 100644 --- a/uchiwa/stash.go +++ b/uchiwa/stash.go @@ -3,7 +3,7 @@ package uchiwa import ( "fmt" - "github.com/sensu/uchiwa/uchiwa/logger" + log "github.com/Sirupsen/logrus" ) type stash struct { @@ -17,13 +17,13 @@ type stash struct { func (u *Uchiwa) PostStash(data stash) error { api, err := getAPI(u.Datacenters, data.Dc) if err != nil { - logger.Warning(err) + log.Warn(err) return err } _, err = api.CreateStash(data) if err != nil { - logger.Warning(err) + log.Warn(err) return err } @@ -50,7 +50,9 @@ func (u *Uchiwa) findStash(path string) ([]interface{}, error) { for _, c := range u.Data.Stashes { m, ok := c.(map[string]interface{}) if !ok { - logger.Warningf("Could not assert this stash to an interface %+v", c) + log.WithFields(log.Fields{ + "stash": c, + }).Warn("Could not assert this stash to an interface.") continue } if m["path"] == path {