From 4766ac337083c13431625d7da477a3fe256ae509 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Sun, 16 Mar 2025 17:54:51 +0300 Subject: [PATCH] chore: use zerolog instead of logrus --- go.mod | 6 +++++- go.sum | 14 ++++++++++++++ handler/document.go | 22 +++++++++++----------- handler/document_test.go | 11 ++++++----- internal/storage/memcached.go | 4 ++-- internal/storage/mongodb.go | 7 ++++--- internal/storage/postgres.go | 8 ++++---- internal/storage/redis.go | 5 +++-- internal/storage/s3.go | 8 ++++---- 9 files changed, 53 insertions(+), 32 deletions(-) diff --git a/go.mod b/go.mod index 2aa1ebc..a2ec2df 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/jackc/pgx/v5 v5.7.2 github.com/prometheus/client_golang v1.21.1 github.com/redis/go-redis/v9 v9.7.1 - github.com/sirupsen/logrus v1.9.3 + github.com/rs/zerolog v1.33.0 github.com/stretchr/testify v1.10.0 github.com/testcontainers/testcontainers-go v0.35.0 github.com/testcontainers/testcontainers-go/modules/minio v0.35.0 @@ -54,6 +54,7 @@ require ( github.com/docker/go-connections v0.5.0 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-chi/httprate v0.14.1 // indirect github.com/go-logr/logr v1.4.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect @@ -66,6 +67,8 @@ require ( github.com/klauspost/compress v1.17.11 // indirect github.com/lufia/plan9stats v0.0.0-20240226150601-1dcf7310316a // indirect github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/patternmatcher v0.6.0 // indirect github.com/moby/sys/sequential v0.5.0 // indirect @@ -83,6 +86,7 @@ require ( github.com/prometheus/procfs v0.15.1 // indirect github.com/shirou/gopsutil/v3 v3.24.2 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect github.com/tklauser/go-sysconf v0.3.13 // indirect github.com/tklauser/numcpus v0.7.0 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect diff --git a/go.sum b/go.sum index 090e8fe..692bf3a 100644 --- a/go.sum +++ b/go.sum @@ -62,6 +62,7 @@ github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= @@ -85,6 +86,8 @@ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2 github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/go-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8= github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= +github.com/go-chi/httprate v0.14.1 h1:EKZHYEZ58Cg6hWcYzoZILsv7ppb46Wt4uQ738IRtpZs= +github.com/go-chi/httprate v0.14.1/go.mod h1:TUepLXaz/pCjmCtf/obgOQJ2Sz6rC8fSf5cAt5cnTt0= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -93,6 +96,7 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= @@ -132,6 +136,11 @@ github.com/lufia/plan9stats v0.0.0-20240226150601-1dcf7310316a h1:3Bm7EwfUQUvhNe github.com/lufia/plan9stats v0.0.0-20240226150601-1dcf7310316a/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= github.com/minio/minio-go/v7 v7.0.68 h1:hTqSIfLlpXaKuNy4baAp4Jjy2sqZEN9hRxD0M4aOfrQ= @@ -181,6 +190,8 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= +github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/shirou/gopsutil/v3 v3.24.2 h1:kcR0erMbLg5/3LcInpw0X/rrPSqq4CDPyI6A6ZRC18Y= github.com/shirou/gopsutil/v3 v3.24.2/go.mod h1:tSg/594BcA+8UdQU2XcW803GWYgdtauFFPgJCJKZlVk= github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= @@ -278,9 +289,12 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc 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.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/handler/document.go b/handler/document.go index 95b0269..7eb2500 100644 --- a/handler/document.go +++ b/handler/document.go @@ -10,7 +10,7 @@ import ( "github.com/armbian/ansi-hastebin/internal/keygenerator" "github.com/armbian/ansi-hastebin/internal/storage" "github.com/go-chi/chi/v5" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" ) // DocumentHandler manages document operations @@ -50,7 +50,7 @@ func (h *DocumentHandler) HandleGet(w http.ResponseWriter, r *http.Request) { data, err := h.Store.Get(key, false) if data != "" && err == nil { - logrus.WithField("key", key).Info("Retrieved document") + log.Info().Str("key", key).Msg("Retrieved document") w.Header().Set("Content-Type", "application/json") if r.Method == http.MethodHead { w.WriteHeader(http.StatusOK) @@ -58,18 +58,18 @@ func (h *DocumentHandler) HandleGet(w http.ResponseWriter, r *http.Request) { } json.NewEncoder(w).Encode(map[string]string{"data": data, "key": key}) } else { - logrus.WithField("key", key).Warn("Document not found") + log.Info().Str("key", key).Msg("Document not found") http.Error(w, `{"message": "Document not found."}`, http.StatusNotFound) } } // Handle retrieving raw document func (h *DocumentHandler) HandleRawGet(w http.ResponseWriter, r *http.Request) { - key := strings.Split(chi.URLParam(r, "id"), ".")[0] data, err := h.Store.Get(key, false) + if data != "" && err == nil { - logrus.WithField("key", key).Info("Retrieved raw document") + log.Info().Str("key", key).Msg("Retrieved raw document") w.Header().Set("Content-Type", "text/plain; charset=UTF-8") if r.Method == http.MethodHead { w.WriteHeader(http.StatusOK) @@ -77,7 +77,7 @@ func (h *DocumentHandler) HandleRawGet(w http.ResponseWriter, r *http.Request) { } w.Write([]byte(data)) } else { - logrus.WithField("key", key).Warn("Raw document not found") + log.Info().Str("key", key).Msg("Raw document not found") http.Error(w, `{"message": "Document not found."}`, http.StatusNotFound) } } @@ -91,7 +91,7 @@ func (h *DocumentHandler) HandlePost(w http.ResponseWriter, r *http.Request) { } if h.MaxLength > 0 && buffer.Len() > h.MaxLength { - logrus.Warn("Document exceeds max length") + log.Info().Str("key", "").Msg("Document exceeds max length") http.Error(w, `{"message": "Document exceeds maximum length."}`, http.StatusBadRequest) return } @@ -99,7 +99,7 @@ func (h *DocumentHandler) HandlePost(w http.ResponseWriter, r *http.Request) { key := h.KeyGenerator.Generate(h.KeyLength) h.Store.Set(key, buffer.String(), false) - logrus.WithField("key", key).Info("Added document") + log.Info().Str("key", key).Msg("Added document") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"key": key}) } @@ -113,7 +113,7 @@ func (h *DocumentHandler) HandlePutLog(w http.ResponseWriter, r *http.Request) { } if h.MaxLength > 0 && buffer.Len() > h.MaxLength { - logrus.Warn("Document exceeds max length") + log.Info().Str("key", "").Msg("Document exceeds max length") http.Error(w, `{"message": "Document exceeds maximum length."}`, http.StatusBadRequest) return } @@ -121,7 +121,7 @@ func (h *DocumentHandler) HandlePutLog(w http.ResponseWriter, r *http.Request) { key := h.KeyGenerator.Generate(h.KeyLength) h.Store.Set(key, buffer.String(), false) - logrus.WithField("key", key).Info("Added document with log link") + log.Info().Str("key", key).Msg("Added document with log link") w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "\nhttps://%s/%s\n\n", r.Host, key) } @@ -136,7 +136,7 @@ func (h *DocumentHandler) readBody(r *http.Request, buffer *strings.Builder) err } else { data, err := io.ReadAll(r.Body) if err != nil { - logrus.Error("Connection error: ", err) + log.Error().Err(err).Msg("Error reading request body") return err } buffer.WriteString(string(data)) diff --git a/handler/document_test.go b/handler/document_test.go index fbbb5b5..b754cf1 100644 --- a/handler/document_test.go +++ b/handler/document_test.go @@ -10,7 +10,8 @@ import ( "testing" "github.com/go-chi/chi/v5" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" ) @@ -176,7 +177,7 @@ func BenchmarkHandlePost(b *testing.B) { handler.RegisterRoutes(router) // Disable logging for benchmark - logrus.StandardLogger().Level = logrus.FatalLevel + log.Logger = log.Level(zerolog.Disabled) body := bytes.NewBufferString("benchmark content") for i := 0; i < b.N; i++ { @@ -190,7 +191,7 @@ func BenchmarkHandleGet(b *testing.B) { handler.RegisterRoutes(router) // Disable logging for benchmark - logrus.StandardLogger().Level = logrus.FatalLevel + log.Logger = log.Level(zerolog.Disabled) // Add document handler.Store.Set("test123", "benchmark data", false) @@ -206,7 +207,7 @@ func BenchmarkHandlePutLog(b *testing.B) { handler.RegisterRoutes(router) // Disable logging for benchmark - logrus.StandardLogger().Level = logrus.FatalLevel + log.Logger = log.Level(zerolog.Disabled) body := bytes.NewBufferString("benchmark log entry") for i := 0; i < b.N; i++ { @@ -220,7 +221,7 @@ func BenchmarkHandleRawGet(b *testing.B) { handler.RegisterRoutes(router) // Disable logging for benchmark - logrus.StandardLogger().Level = logrus.FatalLevel + log.Logger = log.Level(zerolog.Disabled) // Add document handler.Store.Set("test123", "benchmark data", false) diff --git a/internal/storage/memcached.go b/internal/storage/memcached.go index 83c33b5..6a89424 100644 --- a/internal/storage/memcached.go +++ b/internal/storage/memcached.go @@ -4,7 +4,7 @@ import ( "strconv" "github.com/bradfitz/gomemcache/memcache" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" ) type MemcachedStorage struct { @@ -17,7 +17,7 @@ func NewMemcachedStorage(host string, port int, expiration int) *MemcachedStorag // Check if connection is established if err := client.Ping(); err != nil { - logrus.Fatalf("Failed to connect to Memcached: %v", err) + log.Error().Err(err).Msg("Failed to connect to Memcached") } return &MemcachedStorage{client: client, expiration: expiration} diff --git a/internal/storage/mongodb.go b/internal/storage/mongodb.go index 8044262..a43c69d 100644 --- a/internal/storage/mongodb.go +++ b/internal/storage/mongodb.go @@ -6,7 +6,8 @@ import ( "strconv" "time" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" @@ -45,12 +46,12 @@ func NewMongoDBStorage(host string, port int, username string, password string, client, err := mongo.Connect(options.Client().ApplyURI(dsn)) if err != nil { - logrus.Fatalf("Failed to connect to MongoDB: %v", err) + log.Fatal().Err(err).Msg("Failed to connect to MongoDB") } // Check if connection is established if err := client.Ping(ctx, nil); err != nil { - logrus.Fatalf("Failed to connect to MongoDB: %v", err) + log.Fatal().Err(err).Msg("Failed to connect to MongoDB") } db := client.Database(database) diff --git a/internal/storage/postgres.go b/internal/storage/postgres.go index 5f5ed4c..d162147 100644 --- a/internal/storage/postgres.go +++ b/internal/storage/postgres.go @@ -6,7 +6,7 @@ import ( "time" "github.com/jackc/pgx/v5/pgxpool" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" ) const setSQLQuery = "INSERT INTO entries (key, value, expiration) VALUES ($1, $2, $3) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, expiration = EXCLUDED.expiration" @@ -25,18 +25,18 @@ func NewPostgresStorage(host string, port int, username string, passowrd string, dsn := "postgres://" + username + ":" + passowrd + "@" + host + ":" + strconv.Itoa(port) + "/" + database pool, err := pgxpool.New(context.Background(), dsn) if err != nil { - logrus.Fatalf("Failed to connect to PostgreSQL: %v", err) + log.Fatal().Err(err).Msg("Failed to connect to PostgreSQL") } // Check if connection is established if err := pool.Ping(context.Background()); err != nil { - logrus.Fatalf("Failed to connect to PostgreSQL: %v", err) + log.Fatal().Err(err).Msg("Failed to connect to PostgreSQL") } // Create table if not exists _, err = pool.Exec(context.Background(), "CREATE TABLE IF NOT EXISTS entries (id SERIAL PRIMARY KEY, key VARCHAR(255) NOT NULL UNIQUE, value TEXT, expiration BIGINT)") if err != nil { - logrus.Fatalf("Failed to create table: %v", err) + log.Fatal().Err(err).Msg("Failed to create table") } return &PostgresStorage{pool: pool, expiration: expiration} diff --git a/internal/storage/redis.go b/internal/storage/redis.go index 0e97a55..a13d0d7 100644 --- a/internal/storage/redis.go +++ b/internal/storage/redis.go @@ -5,8 +5,9 @@ import ( "strconv" "time" + "github.com/rs/zerolog/log" + "github.com/redis/go-redis/v9" - "github.com/sirupsen/logrus" ) type RedisStorage struct { @@ -26,7 +27,7 @@ func NewRedisStorage(host string, port int, username string, password string, ex // Check if connection is established with 5s timeout if status := client.Ping(ctx); status.Err() != nil { - logrus.Fatalf("Failed to connect to Redis: %v", status.Err()) + log.Fatal().Err(status.Err()).Msg("Failed to connect to Redis") } return &RedisStorage{client: client, expiration: expiration} diff --git a/internal/storage/s3.go b/internal/storage/s3.go index ef31cda..25d11e7 100644 --- a/internal/storage/s3.go +++ b/internal/storage/s3.go @@ -13,7 +13,7 @@ import ( "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" - "github.com/sirupsen/logrus" + "github.com/rs/zerolog/log" ) type S3Storage struct { @@ -34,7 +34,7 @@ func NewS3Storage(host string, port int, username string, password string, regio ) if err != nil { - logrus.Fatalf("unable to load SDK config, %v", err) + log.Fatal().Err(err).Msg("Failed to load SDK config") } svc := s3.NewFromConfig(awscfg, func(o *s3.Options) { @@ -48,7 +48,7 @@ func NewS3Storage(host string, port int, username string, password string, regio // Check if connection is established _, err = svc.ListBuckets(context.Background(), &s3.ListBucketsInput{}) if err != nil { - logrus.Fatalf("Failed to connect to S3: %v", err) + log.Fatal().Err(err).Msg("Failed to connect to S3") } // Create bucket if not exists @@ -56,7 +56,7 @@ func NewS3Storage(host string, port int, username string, password string, regio Bucket: &bucket, }) if err != nil { - logrus.Fatalf("Failed to create bucket: %v", err) + log.Fatal().Err(err).Msg("Failed to create bucket") } return &S3Storage{svc: svc, downloader: downloader, uploader: uploader, bucket: bucket}