From fc0e32405515ab40f6f960f476970652a5e27ac5 Mon Sep 17 00:00:00 2001 From: Harshit mahjan Date: Tue, 16 Jun 2020 10:13:56 +0530 Subject: [PATCH] Refactor logging package (#262) (#285) ##### ISSUE TYPE - Refactor Pull Request (#262) ##### SUMMARY Refactor logging package to make log statements simpler. Current format logging.Logger.Info() doesn't look good. We can embed Logrus into pkg/log to import and use it as log.Info() Fixes # - Embed Logrus into pkg/log - Update the reference to new log package - Change the reference everywhere form `logging.Logger.Function() --> log.Function()` --- cmd/botkube/main.go | 16 +-- pkg/bot/mattermost.go | 26 ++-- pkg/bot/slack.go | 28 ++--- pkg/controller/controller.go | 52 ++++---- pkg/controller/upgrade.go | 4 +- pkg/execute/executor.go | 21 ++-- pkg/filterengine/filterengine.go | 6 +- pkg/filterengine/filters/image_tag_checker.go | 4 +- pkg/filterengine/filters/ingress_validator.go | 4 +- pkg/filterengine/filters/namespace_checker.go | 8 +- .../filters/node_event_checker.go | 4 +- .../filters/object_annotation_checker.go | 10 +- pkg/filterengine/filters/pod_label_checker.go | 4 +- pkg/log/log.go | 113 ++++++++++++++++++ pkg/logging/logging.go | 43 ------- pkg/notify/elasticsearch.go | 14 +-- pkg/notify/mattermost.go | 14 +-- pkg/notify/slack.go | 18 +-- pkg/notify/webhook.go | 8 +- pkg/utils/utils.go | 52 ++++---- 20 files changed, 259 insertions(+), 190 deletions(-) create mode 100644 pkg/log/log.go delete mode 100644 pkg/logging/logging.go diff --git a/cmd/botkube/main.go b/cmd/botkube/main.go index 2c020fb..9dda87b 100644 --- a/cmd/botkube/main.go +++ b/cmd/botkube/main.go @@ -26,7 +26,7 @@ import ( "github.com/infracloudio/botkube/pkg/bot" "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/controller" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/infracloudio/botkube/pkg/metrics" "github.com/infracloudio/botkube/pkg/notify" "github.com/infracloudio/botkube/pkg/utils" @@ -37,20 +37,20 @@ const ( ) func main() { - log.Logger.Info("Starting controller") + log.Info("Starting controller") conf, err := config.New() if err != nil { - log.Logger.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) + log.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) } if conf.Communications.Slack.Enabled { - log.Logger.Info("Starting slack bot") + log.Info("Starting slack bot") sb := bot.NewSlackBot(conf) go sb.Start() } if conf.Communications.Mattermost.Enabled { - log.Logger.Info("Starting mattermost bot") + log.Info("Starting mattermost bot") mb := bot.NewMattermostBot(conf) go mb.Start() } @@ -65,7 +65,7 @@ func main() { notifiers := listNotifiers(conf) // Start upgrade notifier if conf.Settings.UpgradeNotifier { - log.Logger.Info("Starting upgrade notifier") + log.Info("Starting upgrade notifier") go controller.UpgradeNotifier(conf, notifiers) } @@ -84,14 +84,14 @@ func listNotifiers(conf *config.Config) []notify.Notifier { if notifier, err := notify.NewMattermost(conf); err == nil { notifiers = append(notifiers, notifier) } else { - log.Logger.Error(fmt.Sprintf("Failed to create Mattermost client. Error: %v", err)) + log.Error(fmt.Sprintf("Failed to create Mattermost client. Error: %v", err)) } } if conf.Communications.ElasticSearch.Enabled { if els, err := notify.NewElasticSearch(conf); err == nil { notifiers = append(notifiers, els) } else { - log.Logger.Error(fmt.Sprintf("Failed to create els client. Error: %v", err)) + log.Error(fmt.Sprintf("Failed to create els client. Error: %v", err)) } } if conf.Communications.Webhook.Enabled { diff --git a/pkg/bot/mattermost.go b/pkg/bot/mattermost.go index 9d5c4ca..6063f39 100644 --- a/pkg/bot/mattermost.go +++ b/pkg/bot/mattermost.go @@ -25,7 +25,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/execute" - "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/mattermost/mattermost-server/model" ) @@ -93,7 +93,7 @@ func (b *MMBot) Start() { // Check if Mattermost URL is valid checkURL, err := url.Parse(b.ServerURL) if err != nil { - logging.Logger.Errorf("The Mattermost URL entered is incorrect. URL: %s. Error: %s", b.ServerURL, err.Error()) + log.Errorf("The Mattermost URL entered is incorrect. URL: %s. Error: %s", b.ServerURL, err.Error()) return } @@ -106,7 +106,7 @@ func (b *MMBot) Start() { // Check connection to Mattermost server err = b.checkServerConnection() if err != nil { - logging.Logger.Fatalf("There was a problem pinging the Mattermost server URL %s. %s", b.ServerURL, err.Error()) + log.Fatalf("There was a problem pinging the Mattermost server URL %s. %s", b.ServerURL, err.Error()) return } @@ -114,12 +114,12 @@ func (b *MMBot) Start() { // It is obeserved that Mattermost server closes connections unexpectedly after some time. // For now, we are adding retry logic to reconnect to the server // https://github.com/infracloudio/botkube/issues/201 - logging.Logger.Info("BotKube connected to Mattermost!") + log.Info("BotKube connected to Mattermost!") for { var appErr *model.AppError b.WSClient, appErr = model.NewWebSocketClient4(b.WebSocketURL, b.APIClient.AuthToken) if appErr != nil { - logging.Logger.Errorf("Error creating WebSocket for Mattermost connectivity. %v", appErr) + log.Errorf("Error creating WebSocket for Mattermost connectivity. %v", appErr) return } b.listen() @@ -144,7 +144,7 @@ func (mm *mattermostMessage) handleMessage(b MMBot) { if mm.Event.Broadcast.ChannelId == b.getChannel().Id { mm.IsAuthChannel = true } - logging.Logger.Debugf("Received mattermost event: %+v", mm.Event.Data) + log.Debugf("Received mattermost event: %+v", mm.Event.Data) // Trim the @BotKube prefix if exists mm.Request = strings.TrimPrefix(post.Message, "@"+BotName+" ") @@ -162,11 +162,11 @@ func (mm mattermostMessage) sendMessage() { if len(mm.Response) >= 3990 { res, resp := mm.APIClient.UploadFileAsRequestBody([]byte(mm.Response), mm.Event.Broadcast.ChannelId, mm.Request) if resp.Error != nil { - logging.Logger.Error("Error occured while uploading file. Error: ", resp.Error) + log.Error("Error occured while uploading file. Error: ", resp.Error) } post.FileIds = []string{string(res.FileInfos[0].Id)} } else if len(mm.Response) == 0 { - logging.Logger.Info("Invalid request. Dumping the response") + log.Info("Invalid request. Dumping the response") return } else { post.Message = "```\n" + mm.Response + "\n```" @@ -174,7 +174,7 @@ func (mm mattermostMessage) sendMessage() { // Create a post in the Channel if _, resp := mm.APIClient.CreatePost(post); resp.Error != nil { - logging.Logger.Error("Failed to send message. Error: ", resp.Error) + log.Error("Failed to send message. Error: ", resp.Error) } } @@ -197,7 +197,7 @@ func (b MMBot) checkServerConnection() error { func (b MMBot) getTeam() *model.Team { botTeam, resp := b.APIClient.GetTeamByName(b.TeamName, "") if resp.Error != nil { - logging.Logger.Fatalf("There was a problem finding Mattermost team %s. %s", b.TeamName, resp.Error) + log.Fatalf("There was a problem finding Mattermost team %s. %s", b.TeamName, resp.Error) } return botTeam } @@ -206,7 +206,7 @@ func (b MMBot) getTeam() *model.Team { func (b MMBot) getUser() *model.User { users, resp := b.APIClient.AutocompleteUsersInTeam(b.getTeam().Id, BotName, 1, "") if resp.Error != nil { - logging.Logger.Fatalf("There was a problem finding Mattermost user %s. %s", BotName, resp.Error) + log.Fatalf("There was a problem finding Mattermost user %s. %s", BotName, resp.Error) } return users.Users[0] } @@ -216,7 +216,7 @@ func (b MMBot) getChannel() *model.Channel { // Checking if channel exists botChannel, resp := b.APIClient.GetChannelByName(b.ChannelName, b.getTeam().Id, "") if resp.Error != nil { - logging.Logger.Fatalf("There was a problem finding Mattermost channel %s. %s", b.ChannelName, resp.Error) + log.Fatalf("There was a problem finding Mattermost channel %s. %s", b.ChannelName, resp.Error) } // Adding Botkube user to channel @@ -229,7 +229,7 @@ func (b MMBot) listen() { defer b.WSClient.Close() for { if b.WSClient.ListenError != nil { - logging.Logger.Debugf("Mattermost websocket listen error %s. Reconnecting...", b.WSClient.ListenError) + log.Debugf("Mattermost websocket listen error %s. Reconnecting...", b.WSClient.ListenError) return } diff --git a/pkg/bot/slack.go b/pkg/bot/slack.go index efac0fb..7aa1140 100644 --- a/pkg/bot/slack.go +++ b/pkg/bot/slack.go @@ -24,7 +24,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/execute" - "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/nlopes/slack" ) @@ -73,7 +73,7 @@ func (b *SlackBot) Start() { } else { authResp, err := api.AuthTest() if err != nil { - logging.Logger.Fatal(err) + log.Fatal(err) } botID = authResp.UserID } @@ -84,7 +84,7 @@ func (b *SlackBot) Start() { for msg := range RTM.IncomingEvents { switch ev := msg.Data.(type) { case *slack.ConnectedEvent: - logging.Logger.Info("BotKube connected to Slack!") + log.Info("BotKube connected to Slack!") case *slack.MessageEvent: // Skip if message posted by BotKube @@ -100,25 +100,25 @@ func (b *SlackBot) Start() { sm.HandleMessage(b) case *slack.RTMError: - logging.Logger.Errorf("Slack RMT error: %+v", ev.Error()) + log.Errorf("Slack RMT error: %+v", ev.Error()) case *slack.ConnectionErrorEvent: - logging.Logger.Errorf("Slack connection error: %+v", ev.Error()) + log.Errorf("Slack connection error: %+v", ev.Error()) case *slack.IncomingEventError: - logging.Logger.Errorf("Slack incoming event error: %+v", ev.Error()) + log.Errorf("Slack incoming event error: %+v", ev.Error()) case *slack.OutgoingErrorEvent: - logging.Logger.Errorf("Slack outgoing event error: %+v", ev.Error()) + log.Errorf("Slack outgoing event error: %+v", ev.Error()) case *slack.UnmarshallingErrorEvent: - logging.Logger.Errorf("Slack unmarshalling error: %+v", ev.Error()) + log.Errorf("Slack unmarshalling error: %+v", ev.Error()) case *slack.RateLimitedError: - logging.Logger.Errorf("Slack rate limiting error: %+v", ev.Error()) + log.Errorf("Slack rate limiting error: %+v", ev.Error()) case *slack.InvalidAuthEvent: - logging.Logger.Error("Invalid Credentials") + log.Error("Invalid Credentials") return default: @@ -127,7 +127,7 @@ func (b *SlackBot) Start() { } func (sm *slackMessage) HandleMessage(b *SlackBot) { - logging.Logger.Debugf("Slack incoming message: %+v", sm.Event) + log.Debugf("Slack incoming message: %+v", sm.Event) // Check if message posted in authenticated channel info, err := sm.SlackClient.GetConversationInfo(sm.Event.Channel, true) @@ -171,15 +171,15 @@ func (sm slackMessage) Send() { } _, err := sm.RTM.UploadFile(params) if err != nil { - logging.Logger.Error("Error in uploading file:", err) + log.Error("Error in uploading file:", err) } return } else if len(sm.Response) == 0 { - logging.Logger.Info("Invalid request. Dumping the response") + log.Info("Invalid request. Dumping the response") return } if _, _, err := sm.RTM.PostMessage(sm.Event.Channel, slack.MsgOptionText("```"+sm.Response+"```", false), slack.MsgOptionAsUser(true)); err != nil { - logging.Logger.Error("Error in sending message:", err) + log.Error("Error in sending message:", err) } } diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 4384f86..e03dfa1 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -35,7 +35,7 @@ import ( // Register filters _ "github.com/infracloudio/botkube/pkg/filterengine/filters" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/infracloudio/botkube/pkg/notify" "github.com/infracloudio/botkube/pkg/utils" @@ -63,25 +63,25 @@ func RegisterInformers(c *config.Config, notifiers []notify.Notifier) { // Register informers for resource lifecycle events if len(c.Resources) > 0 { - log.Logger.Info("Registering resource lifecycle informer") + log.Info("Registering resource lifecycle informer") for _, r := range c.Resources { if _, ok := utils.ResourceInformerMap[r.Name]; !ok { continue } - log.Logger.Infof("Adding informer for resource:%s", r.Name) + log.Infof("Adding informer for resource:%s", r.Name) utils.ResourceInformerMap[r.Name].AddEventHandler(registerEventHandlers(c, notifiers, r.Name, r.Events)) } } // Register informers for k8s events - log.Logger.Infof("Registering kubernetes events informer for types: %+v", config.WarningEvent.String()) - log.Logger.Infof("Registering kubernetes events informer for types: %+v", config.NormalEvent.String()) + log.Infof("Registering kubernetes events informer for types: %+v", config.WarningEvent.String()) + log.Infof("Registering kubernetes events informer for types: %+v", config.NormalEvent.String()) utils.KubeInformerFactory.Core().V1().Events().Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { _, err := cache.MetaNamespaceKeyFunc(obj) if err != nil { - log.Logger.Errorf("Failed to get MetaNamespaceKey from event resource") + log.Errorf("Failed to get MetaNamespaceKey from event resource") return } eventObj, ok := obj.(*coreV1.Event) @@ -119,21 +119,21 @@ func registerEventHandlers(c *config.Config, notifiers []notify.Notifier, resour for _, event := range events { if event == config.AllEvent || event == config.CreateEvent { handlerFns.AddFunc = func(obj interface{}) { - log.Logger.Debugf("Processing add to %v", resourceType) + log.Debugf("Processing add to %v", resourceType) sendEvent(obj, nil, c, notifiers, resourceType, config.CreateEvent) } } if event == config.AllEvent || event == config.UpdateEvent { handlerFns.UpdateFunc = func(old, new interface{}) { - log.Logger.Debugf("Processing update to %v\n Object: %+v\n", resourceType, new) + log.Debugf("Processing update to %v\n Object: %+v\n", resourceType, new) sendEvent(new, old, c, notifiers, resourceType, config.UpdateEvent) } } if event == config.AllEvent || event == config.DeleteEvent { handlerFns.DeleteFunc = func(obj interface{}) { - log.Logger.Debugf("Processing delete to %v", resourceType) + log.Debugf("Processing delete to %v", resourceType) sendEvent(obj, nil, c, notifiers, resourceType, config.DeleteEvent) } } @@ -150,22 +150,22 @@ func sendEvent(obj, oldObj interface{}, c *config.Config, notifiers []notify.Not // Skip if ErrorEvent is not configured for the resource if !utils.AllowedEventKindsMap[utils.EventKind{Resource: kind, Namespace: "all", EventType: config.ErrorEvent}] && !utils.AllowedEventKindsMap[utils.EventKind{Resource: kind, Namespace: objectMeta.Namespace, EventType: config.ErrorEvent}] { - log.Logger.Debugf("Ignoring %s to %s/%v in %s namespaces", eventType, kind, objectMeta.Name, objectMeta.Namespace) + log.Debugf("Ignoring %s to %s/%v in %s namespaces", eventType, kind, objectMeta.Name, objectMeta.Namespace) return } default: if !utils.AllowedEventKindsMap[utils.EventKind{Resource: kind, Namespace: "all", EventType: eventType}] && !utils.AllowedEventKindsMap[utils.EventKind{Resource: kind, Namespace: objectMeta.Namespace, EventType: eventType}] { - log.Logger.Debugf("Ignoring %s to %s/%v in %s namespaces", eventType, kind, objectMeta.Name, objectMeta.Namespace) + log.Debugf("Ignoring %s to %s/%v in %s namespaces", eventType, kind, objectMeta.Name, objectMeta.Namespace) return } } - log.Logger.Debugf("Processing %s to %s/%v in %s namespaces", eventType, kind, objectMeta.Name, objectMeta.Namespace) + log.Debugf("Processing %s to %s/%v in %s namespaces", eventType, kind, objectMeta.Name, objectMeta.Namespace) // Check if Notify disabled if !config.Notify { - log.Logger.Debug("Skipping notification") + log.Debug("Skipping notification") return } @@ -175,7 +175,7 @@ func sendEvent(obj, oldObj interface{}, c *config.Config, notifiers []notify.Not // Skip older events if !event.TimeStamp.IsZero() { if event.TimeStamp.Before(startTime) { - log.Logger.Debug("Skipping older events") + log.Debug("Skipping older events") return } } @@ -200,7 +200,7 @@ func sendEvent(obj, oldObj interface{}, c *config.Config, notifiers []notify.Not } } else { // skipping least significant update - log.Logger.Debug("skipping least significant Update event") + log.Debug("skipping least significant Update event") event.Skip = true } } @@ -208,25 +208,25 @@ func sendEvent(obj, oldObj interface{}, c *config.Config, notifiers []notify.Not // Filter events event = filterengine.DefaultFilterEngine.Run(obj, event) if event.Skip { - log.Logger.Debugf("Skipping event: %#v", event) + log.Debugf("Skipping event: %#v", event) return } // Skip unpromoted insignificant InfoEvents if event.Type == config.InfoEvent { - log.Logger.Debugf("Skipping Insignificant InfoEvent: %#v", event) + log.Debugf("Skipping Insignificant InfoEvent: %#v", event) return } if len(event.Kind) <= 0 { - log.Logger.Warn("sendEvent received event with Kind nil. Hence skipping.") + log.Warn("sendEvent received event with Kind nil. Hence skipping.") return } // check if Recommendations are disabled if !c.Recommendations { event.Recommendations = nil - log.Logger.Debug("Skipping Recommendations in Event Notifications") + log.Debug("Skipping Recommendations in Event Notifications") } // Send event over notifiers @@ -237,7 +237,7 @@ func sendEvent(obj, oldObj interface{}, c *config.Config, notifiers []notify.Not func sendMessage(c *config.Config, notifiers []notify.Notifier, msg string) { if len(msg) <= 0 { - log.Logger.Warn("sendMessage received string with length 0. Hence skipping.") + log.Warn("sendMessage received string with length 0. Hence skipping.") return } @@ -253,7 +253,7 @@ func configWatcher(c *config.Config, notifiers []notify.Notifier) { watcher, err := fsnotify.NewWatcher() if err != nil { - log.Logger.Fatal("Failed to create file watcher ", err) + log.Fatal("Failed to create file watcher ", err) } defer watcher.Close() @@ -263,24 +263,24 @@ func configWatcher(c *config.Config, notifiers []notify.Notifier) { select { case _, ok := <-watcher.Events: if !ok { - log.Logger.Errorf("Error in getting events for config file:%s. Error: %s", configFile, err.Error()) + log.Errorf("Error in getting events for config file:%s. Error: %s", configFile, err.Error()) return } - log.Logger.Infof("Config file %s is updated. Hence restarting the Pod", configFile) + log.Infof("Config file %s is updated. Hence restarting the Pod", configFile) done <- true case err, ok := <-watcher.Errors: if !ok { - log.Logger.Errorf("Error in getting events for config file:%s. Error: %s", configFile, err.Error()) + log.Errorf("Error in getting events for config file:%s. Error: %s", configFile, err.Error()) return } } } }() - log.Logger.Infof("Registering watcher on configfile %s", configFile) + log.Infof("Registering watcher on configfile %s", configFile) err = watcher.Add(configFile) if err != nil { - log.Logger.Errorf("Unable to register watch on config file:%s. Error: %s", configFile, err.Error()) + log.Errorf("Unable to register watch on config file:%s. Error: %s", configFile, err.Error()) return } <-done diff --git a/pkg/controller/upgrade.go b/pkg/controller/upgrade.go index 1dac80d..b0bbb09 100644 --- a/pkg/controller/upgrade.go +++ b/pkg/controller/upgrade.go @@ -27,7 +27,7 @@ import ( "github.com/google/go-github/v27/github" "github.com/infracloudio/botkube/pkg/config" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/infracloudio/botkube/pkg/notify" ) @@ -42,7 +42,7 @@ func checkRelease(c *config.Config, notifiers []notify.Notifier) { client := github.NewClient(nil) release, _, err := client.Repositories.GetLatestRelease(ctx, "infracloudio", "botkube") if err == nil { - log.Logger.Debugf(fmt.Sprintf("Upgrade notifier:: latest release info=%+v", release)) + log.Debugf(fmt.Sprintf("Upgrade notifier:: latest release info=%+v", release)) if len(os.Getenv("BOTKUBE_VERSION")) == 0 || release.TagName == nil { return } diff --git a/pkg/execute/executor.go b/pkg/execute/executor.go index 298da08..30cc37c 100644 --- a/pkg/execute/executor.go +++ b/pkg/execute/executor.go @@ -32,8 +32,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" filterengine "github.com/infracloudio/botkube/pkg/filterengine" - "github.com/infracloudio/botkube/pkg/logging" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/infracloudio/botkube/pkg/utils" ) @@ -261,7 +260,7 @@ func runKubectlCommand(args []string, clusterName, defaultNamespace string, isAu runner := NewCommandRunner(kubectlBinary, finalArgs) out, err := runner.Run() if err != nil { - log.Logger.Error("Error in executing kubectl command: ", err) + log.Error("Error in executing kubectl command: ", err) return fmt.Sprintf("Cluster: %s\n%s", clusterName, out+err.Error()) } return fmt.Sprintf("Cluster: %s\n%s", clusterName, out) @@ -279,11 +278,11 @@ func runNotifierCommand(args []string, clusterName string, isAuthChannel bool) s switch args[1] { case Start.String(): config.Notify = true - log.Logger.Info("Notifier enabled") + log.Info("Notifier enabled") return fmt.Sprintf(notifierStartMsg, clusterName) case Stop.String(): config.Notify = false - log.Logger.Info("Notifier disabled") + log.Info("Notifier disabled") return fmt.Sprintf(notifierStopMsg, clusterName) case Status.String(): if config.Notify == false { @@ -293,7 +292,7 @@ func runNotifierCommand(args []string, clusterName string, isAuthChannel bool) s case ShowConfig.String(): out, err := showControllerConfig() if err != nil { - log.Logger.Error("Error in executing showconfig command: ", err) + log.Error("Error in executing showconfig command: ", err) return "Error in getting configuration!" } return fmt.Sprintf("Showing config for cluster '%s'\n\n%s", clusterName, out) @@ -312,7 +311,7 @@ func runFilterCommand(args []string, clusterName string, isAuthChannel bool) str switch args[1] { case FilterList.String(): - log.Logger.Debug("List filters") + log.Debug("List filters") return makeFiltersList() // Enable filter @@ -320,7 +319,7 @@ func runFilterCommand(args []string, clusterName string, isAuthChannel bool) str if len(args) < 3 { return fmt.Sprintf(filterNameMissing, makeFiltersList()) } - log.Logger.Debug("Enable filters", args[2]) + log.Debug("Enable filters", args[2]) if err := filterengine.DefaultFilterEngine.SetFilter(args[2], true); err != nil { return err.Error() } @@ -331,7 +330,7 @@ func runFilterCommand(args []string, clusterName string, isAuthChannel bool) str if len(args) < 3 { return fmt.Sprintf(filterNameMissing, makeFiltersList()) } - log.Logger.Debug("Disabled filters", args[2]) + log.Debug("Disabled filters", args[2]) if err := filterengine.DefaultFilterEngine.SetFilter(args[2], false); err != nil { return err.Error() } @@ -361,7 +360,7 @@ func findBotKubeVersion() (versions string) { // Returns "Server Version: xxxx" k8sVersion, err := runner.Run() if err != nil { - log.Logger.Warn(fmt.Sprintf("Failed to get Kubernetes version: %s", err.Error())) + log.Warn(fmt.Sprintf("Failed to get Kubernetes version: %s", err.Error())) k8sVersion = "Server Version: Unknown\n" } @@ -397,7 +396,7 @@ func runVersionCommand(args []string, clusterName string) string { func showControllerConfig() (configYaml string, err error) { c, err := config.New() if err != nil { - logging.Logger.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) + log.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) } // hide sensitive info diff --git a/pkg/filterengine/filterengine.go b/pkg/filterengine/filterengine.go index 0f6e088..c5f7998 100644 --- a/pkg/filterengine/filterengine.go +++ b/pkg/filterengine/filterengine.go @@ -24,7 +24,7 @@ import ( "reflect" "github.com/infracloudio/botkube/pkg/events" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" ) var ( @@ -63,7 +63,7 @@ func NewDefaultFilter() FilterEngine { // Run run the filters func (f *defaultFilters) Run(object interface{}, event events.Event) events.Event { - log.Logger.Debug("Filterengine running filters") + log.Debug("Filterengine running filters") // Run registered filters for k, v := range f.FiltersMap { if v { @@ -75,7 +75,7 @@ func (f *defaultFilters) Run(object interface{}, event events.Event) events.Even // Register filter to engine func (f *defaultFilters) Register(filter Filter) { - log.Logger.Info("Registering the filter ", reflect.TypeOf(filter).Name()) + log.Info("Registering the filter ", reflect.TypeOf(filter).Name()) f.FiltersMap[filter] = true } diff --git a/pkg/filterengine/filters/image_tag_checker.go b/pkg/filterengine/filters/image_tag_checker.go index 2a9e4f6..4557f61 100644 --- a/pkg/filterengine/filters/image_tag_checker.go +++ b/pkg/filterengine/filters/image_tag_checker.go @@ -26,7 +26,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" "github.com/infracloudio/botkube/pkg/filterengine" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" coreV1 "k8s.io/api/core/v1" ) @@ -68,7 +68,7 @@ func (f ImageTagChecker) Run(object interface{}, event *events.Event) { event.Recommendations = append(event.Recommendations, fmt.Sprintf(":latest tag used in image '%s' of Container '%s' should be avoided.", c.Image, c.Name)) } } - log.Logger.Debug("Image tag filter successful!") + log.Debug("Image tag filter successful!") } // Describe filter diff --git a/pkg/filterengine/filters/ingress_validator.go b/pkg/filterengine/filters/ingress_validator.go index db7c26e..dcb77e0 100644 --- a/pkg/filterengine/filters/ingress_validator.go +++ b/pkg/filterengine/filters/ingress_validator.go @@ -25,7 +25,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" "github.com/infracloudio/botkube/pkg/filterengine" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" networkV1beta1 "k8s.io/api/networking/v1beta1" ) @@ -77,7 +77,7 @@ func (iv IngressValidator) Run(object interface{}, event *events.Event) { event.Recommendations = append(event.Recommendations, fmt.Sprintf("TLS secret %s does not exist", tls.SecretName)) } } - log.Logger.Debug("Ingress Validator filter successful!") + log.Debug("Ingress Validator filter successful!") } // Describe filter diff --git a/pkg/filterengine/filters/namespace_checker.go b/pkg/filterengine/filters/namespace_checker.go index a40f2bb..cd32e38 100644 --- a/pkg/filterengine/filters/namespace_checker.go +++ b/pkg/filterengine/filters/namespace_checker.go @@ -26,7 +26,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" "github.com/infracloudio/botkube/pkg/filterengine" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" ) // NamespaceChecker ignore events from blocklisted namespaces @@ -50,8 +50,8 @@ func (f NamespaceChecker) Run(object interface{}, event *events.Event) { // load config.yaml botkubeConfig, err := config.New() if err != nil { - log.Logger.Errorf(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) - log.Logger.Debug("Skipping ignore namespace filter.") + log.Errorf(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) + log.Debug("Skipping ignore namespace filter.") } if botkubeConfig != nil { for _, resource := range botkubeConfig.Resources { @@ -63,7 +63,7 @@ func (f NamespaceChecker) Run(object interface{}, event *events.Event) { } } } - log.Logger.Debug("Ignore Namespaces filter successful!") + log.Debug("Ignore Namespaces filter successful!") } // Describe filter diff --git a/pkg/filterengine/filters/node_event_checker.go b/pkg/filterengine/filters/node_event_checker.go index 59b3f16..9f9f3e2 100644 --- a/pkg/filterengine/filters/node_event_checker.go +++ b/pkg/filterengine/filters/node_event_checker.go @@ -27,7 +27,7 @@ import ( "github.com/infracloudio/botkube/pkg/filterengine" coreV1 "k8s.io/api/core/v1" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" ) const ( @@ -77,7 +77,7 @@ func (f NodeEventsChecker) Run(object interface{}, event *events.Event) { event.Skip = true } - log.Logger.Debug("Node Critical Event filter successful!") + log.Debug("Node Critical Event filter successful!") } // Describe filter diff --git a/pkg/filterengine/filters/object_annotation_checker.go b/pkg/filterengine/filters/object_annotation_checker.go index 8b2e381..fe97f5d 100644 --- a/pkg/filterengine/filters/object_annotation_checker.go +++ b/pkg/filterengine/filters/object_annotation_checker.go @@ -22,7 +22,7 @@ package filters import ( "github.com/infracloudio/botkube/pkg/events" "github.com/infracloudio/botkube/pkg/filterengine" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/infracloudio/botkube/pkg/utils" metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -55,15 +55,15 @@ func (f ObjectAnnotationChecker) Run(object interface{}, event *events.Event) { // Check annotations in object if isObjectNotifDisabled(obj) { event.Skip = true - log.Logger.Debug("Object Notification Disable through annotations") + log.Debug("Object Notification Disable through annotations") } if channel, ok := reconfigureChannel(obj); ok { event.Channel = channel - log.Logger.Debugf("Redirecting Event Notifications to channel: %s", channel) + log.Debugf("Redirecting Event Notifications to channel: %s", channel) } - log.Logger.Debug("Object annotations filter successful!") + log.Debug("Object annotations filter successful!") } // Describe filter @@ -76,7 +76,7 @@ func (f ObjectAnnotationChecker) Describe() string { func isObjectNotifDisabled(obj metaV1.ObjectMeta) bool { if obj.Annotations[DisableAnnotation] == "true" { - log.Logger.Debug("Skipping Disabled Event Notifications!") + log.Debug("Skipping Disabled Event Notifications!") return true } return false diff --git a/pkg/filterengine/filters/pod_label_checker.go b/pkg/filterengine/filters/pod_label_checker.go index af37b0a..bab028e 100644 --- a/pkg/filterengine/filters/pod_label_checker.go +++ b/pkg/filterengine/filters/pod_label_checker.go @@ -25,7 +25,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" "github.com/infracloudio/botkube/pkg/filterengine" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" coreV1 "k8s.io/api/core/v1" ) @@ -56,7 +56,7 @@ func (f PodLabelChecker) Run(object interface{}, event *events.Event) { if len(podObj.ObjectMeta.Labels) == 0 { event.Recommendations = append(event.Recommendations, fmt.Sprintf("pod '%s' creation without labels should be avoided.", podObj.ObjectMeta.Name)) } - log.Logger.Debug("Pod label filter successful!") + log.Debug("Pod label filter successful!") } // Describe filter diff --git a/pkg/log/log.go b/pkg/log/log.go new file mode 100644 index 0000000..933d608 --- /dev/null +++ b/pkg/log/log.go @@ -0,0 +1,113 @@ +// Copyright (c) 2019 InfraCloud Technologies +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +package log + +import ( + "os" + + "github.com/sirupsen/logrus" +) + +// log object for logging across the pkg/ +var log = logrus.New() + +func init() { + // Output to stdout instead of the default stderr + log.SetOutput(os.Stdout) + + // Only log the warning severity or above. + logLevel, err := logrus.ParseLevel(os.Getenv("LOG_LEVEL")) + if err != nil { + // Set Info level as a default + logLevel = logrus.InfoLevel + } + log.SetLevel(logLevel) + log.Formatter = &logrus.TextFormatter{ForceColors: true, FullTimestamp: true} +} + +// Info map logrus.Info func to log.Info +func Info(message ...interface{}) { + log.Info(message...) +} + +// Trace map logrus.Trace func to log.Trace +func Trace(message ...interface{}) { + log.Trace(message...) +} + +// Debug map logrus.Debug func to log.Debug +func Debug(message ...interface{}) { + log.Debug(message...) +} + +// Warn map logrus.Warn func to log.Warn +func Warn(message ...interface{}) { + log.Warn(message...) +} + +// Error map logrus.Error func to log.Error +func Error(message ...interface{}) { + log.Error(message...) +} + +// Fatal map logrus.Fatal func to log.Fatal +func Fatal(message ...interface{}) { + log.Fatal(message...) +} + +// Panic map logrus.Panic func to log.Panic +func Panic(message ...interface{}) { + log.Panic(message...) +} + +// Infof map logrus.Infof func to log.Infof +func Infof(format string, v ...interface{}) { + log.Infof(format, v...) +} + +// Tracef map logrus.Tracef func to log.Tracef +func Tracef(format string, v ...interface{}) { + log.Tracef(format, v...) +} + +// Debugf map logrus.Debugf func to log.Debugf +func Debugf(format string, v ...interface{}) { + log.Debugf(format, v...) +} + +// Warnf map logrus.Warnf func to log.Warnf +func Warnf(format string, v ...interface{}) { + log.Warnf(format, v...) +} + +// Errorf map logrus.Errorf func to log.Errorf +func Errorf(format string, v ...interface{}) { + log.Errorf(format, v...) +} + +// Fatalf map logrus.Fatalf func to log.Fatalf +func Fatalf(format string, v ...interface{}) { + log.Fatalf(format, v...) +} + +// Panicf map logrus.Panicf func to log.Panicf +func Panicf(format string, v ...interface{}) { + log.Panicf(format, v...) +} diff --git a/pkg/logging/logging.go b/pkg/logging/logging.go deleted file mode 100644 index bb0f329..0000000 --- a/pkg/logging/logging.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2019 InfraCloud Technologies -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -package logging - -import ( - "os" - - "github.com/sirupsen/logrus" -) - -// Logger global object for logging across the pkg/ -var Logger = logrus.New() - -func init() { - // Output to stdout instead of the default stderr - Logger.SetOutput(os.Stdout) - - // Only log the warning severity or above. - logLevel, err := logrus.ParseLevel(os.Getenv("LOG_LEVEL")) - if err != nil { - // Set Info level as a default - logLevel = logrus.InfoLevel - } - Logger.SetLevel(logLevel) - Logger.Formatter = &logrus.TextFormatter{ForceColors: true, FullTimestamp: true} -} diff --git a/pkg/notify/elasticsearch.go b/pkg/notify/elasticsearch.go index 9e3659d..24ed6fc 100644 --- a/pkg/notify/elasticsearch.go +++ b/pkg/notify/elasticsearch.go @@ -25,7 +25,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/olivere/elastic" ) @@ -71,7 +71,7 @@ type index struct { // SendEvent sends event notification to slack func (e *ElasticSearch) SendEvent(event events.Event) (err error) { - log.Logger.Debug(fmt.Sprintf(">> Sending to ElasticSearch: %+v", event)) + log.Debug(fmt.Sprintf(">> Sending to ElasticSearch: %+v", event)) ctx := context.Background() // set missing cluster name to event object @@ -80,7 +80,7 @@ func (e *ElasticSearch) SendEvent(event events.Event) (err error) { // Create index if not exists exists, err := e.ELSClient.IndexExists(e.Index).Do(ctx) if err != nil { - log.Logger.Error(fmt.Sprintf("Failed to get index. Error:%s", err.Error())) + log.Error(fmt.Sprintf("Failed to get index. Error:%s", err.Error())) return err } if !exists { @@ -95,7 +95,7 @@ func (e *ElasticSearch) SendEvent(event events.Event) (err error) { } _, err := e.ELSClient.CreateIndex(e.Index).BodyJson(mapping).Do(ctx) if err != nil { - log.Logger.Error(fmt.Sprintf("Failed to create index. Error:%s", err.Error())) + log.Error(fmt.Sprintf("Failed to create index. Error:%s", err.Error())) return err } } @@ -103,15 +103,15 @@ func (e *ElasticSearch) SendEvent(event events.Event) (err error) { // Send event to els _, err = e.ELSClient.Index().Index(e.Index).Type(e.Type).BodyJson(event).Do(ctx) if err != nil { - log.Logger.Error(fmt.Sprintf("Failed to post data to els. Error:%s", err.Error())) + log.Error(fmt.Sprintf("Failed to post data to els. Error:%s", err.Error())) return err } _, err = e.ELSClient.Flush().Index(e.Index).Do(ctx) if err != nil { - log.Logger.Error(fmt.Sprintf("Failed to flush data to els. Error:%s", err.Error())) + log.Error(fmt.Sprintf("Failed to flush data to els. Error:%s", err.Error())) return err } - log.Logger.Debugf("Event successfully sent to ElasticSearch index %s", e.Index) + log.Debugf("Event successfully sent to ElasticSearch index %s", e.Index) return nil } diff --git a/pkg/notify/mattermost.go b/pkg/notify/mattermost.go index e65c704..16870ca 100644 --- a/pkg/notify/mattermost.go +++ b/pkg/notify/mattermost.go @@ -26,7 +26,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/mattermost/mattermost-server/model" ) @@ -60,7 +60,7 @@ func NewMattermost(c *config.Config) (Notifier, error) { // SendEvent sends event notification to Mattermost func (m *Mattermost) SendEvent(event events.Event) error { - log.Logger.Info(fmt.Sprintf(">> Sending to Mattermost: %+v", event)) + log.Info(fmt.Sprintf(">> Sending to Mattermost: %+v", event)) var fields []*model.SlackAttachmentField @@ -95,7 +95,7 @@ func (m *Mattermost) SendEvent(event events.Event) error { post.ChannelId = event.Channel if _, resp := m.Client.CreatePost(post); resp.Error != nil { - log.Logger.Error("Failed to send message. Error: ", resp.Error) + log.Error("Failed to send message. Error: ", resp.Error) // send error message to default channel msg := fmt.Sprintf("Unable to send message to Channel `%s`: `%s`\n```add Botkube app to the Channel %s\nMissed events follows below:```", event.Channel, resp.Error, event.Channel) go m.SendMessage(msg) @@ -105,15 +105,15 @@ func (m *Mattermost) SendEvent(event events.Event) error { go m.SendEvent(event) return resp.Error } - log.Logger.Debugf("Event successfully sent to channel %s", post.ChannelId) + log.Debugf("Event successfully sent to channel %s", post.ChannelId) } else { post.ChannelId = m.Channel // empty value in event.channel sends notifications to default channel. if _, resp := m.Client.CreatePost(post); resp.Error != nil { - log.Logger.Error("Failed to send message. Error: ", resp.Error) + log.Error("Failed to send message. Error: ", resp.Error) return resp.Error } - log.Logger.Debugf("Event successfully sent to channel %s", post.ChannelId) + log.Debugf("Event successfully sent to channel %s", post.ChannelId) } return nil } @@ -124,7 +124,7 @@ func (m *Mattermost) SendMessage(msg string) error { post.ChannelId = m.Channel post.Message = msg if _, resp := m.Client.CreatePost(post); resp.Error != nil { - log.Logger.Error("Failed to send message. Error: ", resp.Error) + log.Error("Failed to send message. Error: ", resp.Error) } return nil } diff --git a/pkg/notify/slack.go b/pkg/notify/slack.go index c83e8d5..8818a0b 100644 --- a/pkg/notify/slack.go +++ b/pkg/notify/slack.go @@ -26,7 +26,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" "github.com/nlopes/slack" ) @@ -57,7 +57,7 @@ func NewSlack(c *config.Config) Notifier { // SendEvent sends event notification to slack func (s *Slack) SendEvent(event events.Event) error { - log.Logger.Debug(fmt.Sprintf(">> Sending to slack: %+v", event)) + log.Debug(fmt.Sprintf(">> Sending to slack: %+v", event)) api := slack.New(s.Token) if len(s.SlackURL) != 0 { @@ -69,7 +69,7 @@ func (s *Slack) SendEvent(event events.Event) error { if event.Channel != "" { channelID, timestamp, err := api.PostMessage(event.Channel, slack.MsgOptionAttachments(attachment), slack.MsgOptionAsUser(true)) if err != nil { - log.Logger.Errorf("Error in sending slack message %s", err.Error()) + log.Errorf("Error in sending slack message %s", err.Error()) // send error message to default channel if err.Error() == "channel_not_found" { msg := fmt.Sprintf("Unable to send message to Channel `%s`: `%s`\n```add Botkube app to the Channel %s\nMissed events follows below:```", event.Channel, err.Error(), event.Channel) @@ -81,22 +81,22 @@ func (s *Slack) SendEvent(event events.Event) error { } return err } - log.Logger.Debugf("Event successfully sent to channel %s at %s", channelID, timestamp) + log.Debugf("Event successfully sent to channel %s at %s", channelID, timestamp) } else { // empty value in event.channel sends notifications to default channel. channelID, timestamp, err := api.PostMessage(s.Channel, slack.MsgOptionAttachments(attachment), slack.MsgOptionAsUser(true)) if err != nil { - log.Logger.Errorf("Error in sending slack message %s", err.Error()) + log.Errorf("Error in sending slack message %s", err.Error()) return err } - log.Logger.Debugf("Event successfully sent to channel %s at %s", channelID, timestamp) + log.Debugf("Event successfully sent to channel %s at %s", channelID, timestamp) } return nil } // SendMessage sends message to slack channel func (s *Slack) SendMessage(msg string) error { - log.Logger.Debug(fmt.Sprintf(">> Sending to slack: %+v", msg)) + log.Debug(fmt.Sprintf(">> Sending to slack: %+v", msg)) api := slack.New(s.Token) if len(s.SlackURL) != 0 { @@ -105,11 +105,11 @@ func (s *Slack) SendMessage(msg string) error { channelID, timestamp, err := api.PostMessage(s.Channel, slack.MsgOptionText(msg, false), slack.MsgOptionAsUser(true)) if err != nil { - log.Logger.Errorf("Error in sending slack message %s", err.Error()) + log.Errorf("Error in sending slack message %s", err.Error()) return err } - log.Logger.Debugf("Message successfully sent to channel %s at %s", channelID, timestamp) + log.Debugf("Message successfully sent to channel %s at %s", channelID, timestamp) return nil } diff --git a/pkg/notify/webhook.go b/pkg/notify/webhook.go index 547242c..d9485b3 100644 --- a/pkg/notify/webhook.go +++ b/pkg/notify/webhook.go @@ -28,7 +28,7 @@ import ( "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/events" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" ) // Webhook contains URL and ClusterName @@ -100,11 +100,11 @@ func (w *Webhook) SendEvent(event events.Event) (err error) { err = w.PostWebhook(jsonPayload) if err != nil { - log.Logger.Error(err.Error()) - log.Logger.Debugf("Event Not Sent to Webhook %v", event) + log.Error(err.Error()) + log.Debugf("Event Not Sent to Webhook %v", event) } - log.Logger.Debugf("Event successfully sent to Webhook %v", event) + log.Debugf("Event successfully sent to Webhook %v", event) return nil } diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 9331795..5d57061 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -27,7 +27,7 @@ import ( "time" "github.com/infracloudio/botkube/pkg/config" - log "github.com/infracloudio/botkube/pkg/logging" + "github.com/infracloudio/botkube/pkg/log" appsV1 "k8s.io/api/apps/v1" batchV1 "k8s.io/api/batch/v1" coreV1 "k8s.io/api/core/v1" @@ -64,16 +64,16 @@ func InitKubeClient() { } botkubeConf, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath) if err != nil { - log.Logger.Fatal(err) + log.Fatal(err) } KubeClient, err = kubernetes.NewForConfig(botkubeConf) if err != nil { - log.Logger.Fatal(err) + log.Fatal(err) } } else { KubeClient, err = kubernetes.NewForConfig(kubeConfig) if err != nil { - log.Logger.Fatal(err) + log.Fatal(err) } } } @@ -95,7 +95,7 @@ type KindNS struct { func InitInformerMap() { conf, err := config.New() if err != nil { - log.Logger.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) + log.Fatal(fmt.Sprintf("Error in loading configuration. Error:%s", err.Error())) } // Get resync period @@ -105,7 +105,7 @@ func InitInformerMap() { } rsyncTime, err := strconv.Atoi(rsyncTimeStr) if err != nil { - log.Logger.Fatal("Error in reading INFORMERS_RESYNC_PERIOD env var.", err) + log.Fatal("Error in reading INFORMERS_RESYNC_PERIOD env var.", err) } // Create shared informer factory @@ -171,8 +171,8 @@ func InitInformerMap() { } } } - log.Logger.Infof("Allowed Events - %+v", AllowedEventKindsMap) - log.Logger.Infof("Allowed UpdateEvents - %+v", AllowedUpdateEventsMap) + log.Infof("Allowed Events - %+v", AllowedEventKindsMap) + log.Infof("Allowed UpdateEvents - %+v", AllowedUpdateEventsMap) } // GetObjectMetaData returns metadata of the given object @@ -314,110 +314,110 @@ func ExtractAnnotaions(obj *coreV1.Event) map[string]string { if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Node": object, err := KubeClient.CoreV1().Nodes().Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Namespace": object, err := KubeClient.CoreV1().Namespaces().Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "PersistentVolume": object, err := KubeClient.CoreV1().PersistentVolumes().Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "PersistentVolumeClaim": object, err := KubeClient.CoreV1().PersistentVolumeClaims(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "ReplicationController": object, err := KubeClient.CoreV1().ReplicationControllers(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Service": object, err := KubeClient.CoreV1().Services(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Secret": object, err := KubeClient.CoreV1().Secrets(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "ConfigMap": object, err := KubeClient.CoreV1().ConfigMaps(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "DaemonSet": object, err := KubeClient.ExtensionsV1beta1().DaemonSets(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Ingress": object, err := KubeClient.ExtensionsV1beta1().Ingresses(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "ReplicaSet": object, err := KubeClient.ExtensionsV1beta1().ReplicaSets(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Deployment": object, err := KubeClient.ExtensionsV1beta1().Deployments(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Job": object, err := KubeClient.BatchV1().Jobs(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "Role": object, err := KubeClient.RbacV1().Roles(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "RoleBinding": object, err := KubeClient.RbacV1().RoleBindings(obj.InvolvedObject.Namespace).Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "ClusterRole": object, err := KubeClient.RbacV1().ClusterRoles().Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) case "ClusterRoleBinding": object, err := KubeClient.RbacV1().ClusterRoleBindings().Get(obj.InvolvedObject.Name, metaV1.GetOptions{}) if err == nil { return object.ObjectMeta.Annotations } - log.Logger.Error(err) + log.Error(err) } return map[string]string{}