Skip to content

Commit

Permalink
use slog default logger (#228)
Browse files Browse the repository at this point in the history
* refactor: use slog improve logs

* use slog default logger

* all notice log debug level
  • Loading branch information
keidarcy authored May 17, 2024
1 parent 5bc10c2 commit 50a48dc
Show file tree
Hide file tree
Showing 32 changed files with 216 additions and 271 deletions.
1 change: 0 additions & 1 deletion .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ changelog:
- '^test:'
- '^deps:'
- '^bump:'
- '^refactor:'
- '^Merge pull request'
- '^Merge branch'

Expand Down
10 changes: 3 additions & 7 deletions cmd/e1s/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"log/slog"
"os"
"path/filepath"

Expand Down Expand Up @@ -92,11 +93,7 @@ Check https://github.com/keidarcy/e1s for more details.`,
shell := viper.GetString("shell")
theme := viper.GetString("theme")

logger, file := utils.GetLogger(logFile, json, debug)
defer file.Close()

option := e1s.Option{
Logger: logger,
ConfigFile: configFile,
LogFile: logFile,
Debug: debug,
Expand All @@ -107,11 +104,10 @@ Check https://github.com/keidarcy/e1s for more details.`,
Theme: theme,
}

logger.Debugf("ConfigFile: %s, LogFile: %s, Debug: %t, JSON: %t, ReadOnly: %t, Refresh: %d, Shell: %s", configFile, logFile, debug, json, readOnly, refresh, shell)
if err := e1s.Start(option); err != nil {
fmt.Printf("e1s failed to start, please check your aws cli credential and permission. error: %v\n", err)
logger.Fatalf("Failed to start, error: %v\n", err)
// will call os.Exit(1)
slog.Error("failed to start", "error", err)
os.Exit(1)
}
},
Version: utils.ShowVersion(),
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ require (
github.com/aws/aws-sdk-go-v2/service/ecs v1.41.6
github.com/aws/aws-sdk-go-v2/service/ssm v1.49.5
github.com/gdamore/tcell/v2 v2.7.4
github.com/lmittmann/tint v1.0.4
github.com/rivo/tview v0.0.0-20240413115534-b0d41c484b95
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.8.0
github.com/spf13/viper v1.18.2
golang.org/x/sync v0.7.0
Expand Down
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lmittmann/tint v1.0.4 h1:LeYihpJ9hyGvE0w+K2okPTGUdVLfng1+nDNVR4vWISc=
github.com/lmittmann/tint v1.0.4/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
Expand All @@ -92,8 +94,6 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
Expand All @@ -110,7 +110,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
Expand Down Expand Up @@ -140,7 +139,6 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
Expand Down
9 changes: 5 additions & 4 deletions internal/api/auto_scaling.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"log/slog"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/applicationautoscaling"
Expand Down Expand Up @@ -61,7 +62,7 @@ func (store *Store) describeScalingActivities(serviceArn *string) ([]types.Scali
activitiesOutput, err := store.autoScaling.DescribeScalingActivities(context.Background(), activitiesInput)

if err != nil {
logger.Warnf("Failed to run aws api to auto scaling activities serviceArn: \"%s\", err: %v", *serviceArn, err)
slog.Warn("failed to run aws api to auto scaling activities", "serviceArn", *serviceArn, "error", err)
return nil, err
}

Expand All @@ -79,7 +80,7 @@ func (store *Store) describeScalableTargets(serviceArn *string) ([]types.Scalabl
targetsOutput, err := store.autoScaling.DescribeScalableTargets(context.Background(), targetsInput)

if err != nil {
logger.Warnf("Failed to run aws api to auto scaling activities serviceArn: \"%s\", err: %v", *serviceArn, err)
slog.Warn("failed to run aws api to auto scaling activities", "serviceArn", *serviceArn, "error", err)
return nil, err
}

Expand All @@ -97,7 +98,7 @@ func (store *Store) describeScalingPolicies(serviceArn *string) ([]types.Scaling
policiesOutput, err := store.autoScaling.DescribeScalingPolicies(context.Background(), policiesInput)

if err != nil {
logger.Warnf("Failed to run aws api to auto scaling activities serviceArn: \"%s\", err: %v", *serviceArn, err)
slog.Warn("failed to run aws api to auto scaling activities", "serviceArn", *serviceArn, "error", err)
return nil, err
}

Expand All @@ -121,7 +122,7 @@ func (store *Store) describeScheduledAction(serviceArn *string) ([]types.Schedul
actionsOutput, err := store.autoScaling.DescribeScheduledActions(context.Background(), actionsInput)

if err != nil {
logger.Warnf("Failed to run aws api to auto scaling scheduled actions serviceArn: \"%s\", err: %v", *serviceArn, err)
slog.Warn("failed to run aws api to auto scaling scheduled actions", "serviceArn", *serviceArn, "error", err)
return nil, err
}

Expand Down
5 changes: 3 additions & 2 deletions internal/api/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"log/slog"
"sort"

"github.com/aws/aws-sdk-go-v2/service/ecs"
Expand All @@ -18,7 +19,7 @@ func (store *Store) ListClusters() ([]types.Cluster, error) {
})

if err != nil {
logger.Warnf("Failed to run aws api to list clusters, err: %v", err)
slog.Warn("failed to run aws api to list clusters", "error", err)
return []types.Cluster{}, err
}

Expand All @@ -38,7 +39,7 @@ func (store *Store) ListClusters() ([]types.Cluster, error) {

describeClusterOutput, err := store.ecs.DescribeClusters(context.Background(), describeInput)
if err != nil {
logger.Warnf("Failed to run aws api to describe clusters, err: %v", err)
slog.Warn("failed to run aws api to describe clusters", "error", err)
return []types.Cluster{}, err
}

Expand Down
7 changes: 4 additions & 3 deletions internal/api/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"log/slog"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
Expand Down Expand Up @@ -31,7 +32,7 @@ func (store *Store) GetLogs(tdArn *string) ([]cloudwatchlogsTypes.OutputLogEvent
td, err := store.DescribeTaskDefinition(tdArn)

if err != nil {
logger.Warnf("Failed to run aws api to describe task definition, err: %v", err)
slog.Warn("failed to run aws api to describe task definition", "error", err)
return nil, err
}

Expand Down Expand Up @@ -63,7 +64,7 @@ func (store *Store) GetLogs(tdArn *string) ([]cloudwatchlogsTypes.OutputLogEvent
}
describeLogStreamsOutput, err := store.cloudwatchlogs.DescribeLogStreams(context.Background(), describeLogStreamsInput)
if err != nil {
logger.Warnf("Failed to run aws api to describe log stream, err: %v", err)
slog.Warn("failed to run aws api to describe log stream", "error", err)
continue
}
streamName := describeLogStreamsOutput.LogStreams[0].LogStreamName
Expand All @@ -75,7 +76,7 @@ func (store *Store) GetLogs(tdArn *string) ([]cloudwatchlogsTypes.OutputLogEvent
}
getLogEventsOutput, err := store.cloudwatchlogs.GetLogEvents(context.Background(), getLogEventsInput)
if err != nil {
logger.Warnf("Failed to run aws api to get log events, err: %v", err)
slog.Warn("failed to run aws api to get log events", "error", err)
continue
}
logs = append(logs, getLogEventsOutput.Events...)
Expand Down
5 changes: 3 additions & 2 deletions internal/api/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"log/slog"
"time"

"github.com/aws/aws-sdk-go-v2/aws"
Expand Down Expand Up @@ -57,7 +58,7 @@ func (store *Store) getCPU(cluster, service *string) ([]types.Datapoint, error)
metricOutput, err := store.cloudwatch.GetMetricStatistics(context.TODO(), statisticsInput)

if err != nil {
logger.Warnf("Failed to run aws api to %s, cluster: \"%s\", service: \"%s\", err: %v", CPU, *cluster, *service, err)
slog.Warn("failed to run aws api", "metrics", CPU, "cluster", *cluster, "service", *service, "error", err)
return nil, err
}

Expand All @@ -82,7 +83,7 @@ func (store *Store) getMemory(cluster, service *string) ([]types.Datapoint, erro
metricOutput, err := store.cloudwatch.GetMetricStatistics(context.TODO(), statisticsInput)

if err != nil {
logger.Warnf("Failed to run aws api to %s, cluster: \"%s\", service: \"%s\", err: %v", Memory, *cluster, *service, err)
slog.Warn("failed to run aws api", "metrics", Memory, "cluster", *cluster, "service", *service, "error", err)
return nil, err
}

Expand Down
24 changes: 13 additions & 11 deletions internal/api/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package api

import (
"context"
"log/slog"
"math"
"sort"

"github.com/aws/aws-sdk-go-v2/service/ecs"
"github.com/aws/aws-sdk-go-v2/service/ecs/types"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)

Expand All @@ -26,7 +26,7 @@ func (store *Store) ListServices(clusterName *string) ([]types.Service, error) {
for {
listServicesOutput, err := store.ecs.ListServices(context.Background(), params)
if err != nil {
logger.Warnf("Failed to run aws api to list services, err: %v", err)
slog.Warn("failed to run aws api to list services", "error", err)
// If first run failed return err
if len(serviceARNs) == 0 {
return []types.Service{}, err
Expand Down Expand Up @@ -79,7 +79,7 @@ func (store *Store) ListServices(clusterName *string) ([]types.Service, error) {
},
})
if err != nil {
logger.Warnf("Failed to run aws api to describe services in i:%d times loop, err: %v", i, err)
slog.Warn("failed to run aws api to describe services in i:%d times loop", "error", i, err)
return err
}

Expand Down Expand Up @@ -121,17 +121,19 @@ func (store *Store) UpdateService(input *ecs.UpdateServiceInput) (*types.Service
desiredCount = int(*input.DesiredCount)
}

logger.WithFields(logrus.Fields{
"Cluster": *input.Cluster,
"Service": *input.Service,
"DesiredCount": desiredCount,
"TaskDefinition": taskDefinition,
"ForceNewDeployment": input.ForceNewDeployment,
}).Info("Update service with following parameters")
slog.Info("update service",
slog.Group("parameters",
slog.String("cluster", *input.Cluster),
slog.String("service", *input.Service),
slog.Int("desiredCount", desiredCount),
slog.String("taskDefinition", taskDefinition),
slog.Bool("forceNewDeployment", input.ForceNewDeployment),
),
)

updateOutput, err := store.ecs.UpdateService(context.Background(), input)
if err != nil {
logger.Warnf("Failed to run aws api to update service, err: %v", err)
slog.Warn("failed to run aws api to update service", "error", err)
return nil, err
}
return updateOutput.Service, nil
Expand Down
9 changes: 6 additions & 3 deletions internal/api/ssm.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"os/exec"
"strings"
Expand Down Expand Up @@ -68,8 +69,9 @@ func (store *Store) StartSession(input *SsmStartSessionInput) (*string, error) {

bin, err := exec.LookPath(smpCi)
if err != nil {
logger.Warnf("Failed to find %s path, please check %s", smpCi, "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html")
return nil, fmt.Errorf("failed to find %s path, please check %s", smpCi, "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html")
m := fmt.Sprintf("failed to find %s path, please check %s", smpCi, "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html")
slog.Warn(m)
return nil, fmt.Errorf(m)
}

region := store.Config.Region
Expand All @@ -92,7 +94,7 @@ func (store *Store) StartSession(input *SsmStartSessionInput) (*string, error) {
fmt.Sprintf("https://ssm.%v.amazonaws.com", region),
}

logger.Infof("Exec: `%s %s`", bin, strings.Join(args, " "))
slog.Info("exec", "command", bin+" "+strings.Join(args, " "))
// start process
cmd := exec.Command(bin, args...)
err = cmd.Start()
Expand All @@ -104,6 +106,7 @@ func (store *Store) TerminateSessions(sessionIds []*string) error {
g := new(errgroup.Group)

for _, id := range sessionIds {
id := id
g.Go(func() error {
input := &ssm.TerminateSessionInput{
SessionId: id,
Expand Down
11 changes: 4 additions & 7 deletions internal/api/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"log/slog"
"os"

"github.com/aws/aws-sdk-go-v2/aws"
Expand All @@ -11,11 +12,8 @@ import (
"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go-v2/service/ecs"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/sirupsen/logrus"
)

var logger *logrus.Logger

type Store struct {
*aws.Config
Region string
Expand All @@ -27,17 +25,16 @@ type Store struct {
ssm *ssm.Client
}

func NewStore(logr *logrus.Logger) (*Store, error) {
logger = logr
func NewStore() (*Store, error) {
profile := os.Getenv("AWS_PROFILE")
region := os.Getenv("AWS_REGION")
cfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(region))
if err != nil {
logger.Errorf("Failed to load aws SDK config, error: %v\n", err)
slog.Error("failed to load aws SDK config", "error", err)
return nil, err
}
ecsClient := ecs.NewFromConfig(cfg)
logger.Infof("e1s load config with AWS_PROFILE: %q, AWS_REGION: %q", profile, cfg.Region)
slog.Info("load config", slog.String("AWS_PROFILE", profile), slog.String("AWS_REGION", cfg.Region))
return &Store{
Config: &cfg,
Region: cfg.Region,
Expand Down
5 changes: 3 additions & 2 deletions internal/api/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"log/slog"
"sort"

"github.com/aws/aws-sdk-go-v2/service/ecs"
Expand All @@ -24,7 +25,7 @@ func (store *Store) ListTasks(clusterName, serviceName *string, status types.Des
MaxResults: &limit,
})
if err != nil {
logger.Warnf("Failed to run aws api to list tasks, err: %v", err)
slog.Warn("failed to run aws api to list tasks", "error", err)
return []types.Task{}, err
}
if len(listTasksOutput.TaskArns) == 0 {
Expand All @@ -44,7 +45,7 @@ func (store *Store) ListTasks(clusterName, serviceName *string, status types.Des
})

if err != nil {
logger.Warnf("Failed to run aws api to describe tasks, error: %v", err)
slog.Warn("failed to run aws api to describe tasks", "error", err)
return []types.Task{}, err
}

Expand Down
Loading

0 comments on commit 50a48dc

Please sign in to comment.