diff --git a/.github/workflows/docker-api-dev.yml b/.github/workflows/docker-api-dev.yml index aa34061..1960d86 100644 --- a/.github/workflows/docker-api-dev.yml +++ b/.github/workflows/docker-api-dev.yml @@ -21,7 +21,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: '1.20' + go-version: '1.21' - name: golangci-lint uses: golangci/golangci-lint-action@v3 diff --git a/.github/workflows/docker-web-dev.yaml b/.github/workflows/docker-web-dev.yaml index 9620b04..2d08c83 100644 --- a/.github/workflows/docker-web-dev.yaml +++ b/.github/workflows/docker-web-dev.yaml @@ -21,7 +21,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: '1.20' + go-version: '1.21' - name: golangci-lint uses: golangci/golangci-lint-action@v3 diff --git a/build/Dockerfile.api b/build/Dockerfile.api index 0a97191..81ea9fd 100644 --- a/build/Dockerfile.api +++ b/build/Dockerfile.api @@ -1,4 +1,4 @@ -FROM golang:1.20 AS builder +FROM golang:1.21 AS builder RUN mkdir -p /app WORKDIR /app diff --git a/build/Dockerfile.web b/build/Dockerfile.web index db50591..7c262e0 100644 --- a/build/Dockerfile.web +++ b/build/Dockerfile.web @@ -1,4 +1,4 @@ -FROM golang:1.20 AS builder +FROM golang:1.21 AS builder RUN mkdir -p /app WORKDIR /app diff --git a/cmd/chat.go b/cmd/chat.go index e98cbc4..b1d2f63 100644 --- a/cmd/chat.go +++ b/cmd/chat.go @@ -1,8 +1,10 @@ package cmd import ( + log "log/slog" + "os" + "github.com/minghsu0107/go-random-chat/internal/wire" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -12,7 +14,8 @@ var chatCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { server, err := wire.InitializeChatServer("chat") if err != nil { - log.Fatal(err) + log.Error(err.Error()) + os.Exit(1) } server.Serve() }, diff --git a/cmd/forwarder.go b/cmd/forwarder.go index 99c0107..5a2331a 100644 --- a/cmd/forwarder.go +++ b/cmd/forwarder.go @@ -1,8 +1,10 @@ package cmd import ( + log "log/slog" + "os" + "github.com/minghsu0107/go-random-chat/internal/wire" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -12,7 +14,8 @@ var forwarderCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { server, err := wire.InitializeForwarderServer("forwarder") if err != nil { - log.Fatal(err) + log.Error(err.Error()) + os.Exit(1) } server.Serve() }, diff --git a/cmd/match.go b/cmd/match.go index 06e95be..589c9df 100644 --- a/cmd/match.go +++ b/cmd/match.go @@ -1,8 +1,10 @@ package cmd import ( + log "log/slog" + "os" + "github.com/minghsu0107/go-random-chat/internal/wire" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -12,7 +14,8 @@ var matchCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { server, err := wire.InitializeMatchServer("match") if err != nil { - log.Fatal(err) + log.Error(err.Error()) + os.Exit(1) } server.Serve() }, diff --git a/cmd/uploader.go b/cmd/uploader.go index aee057f..b8c8f3b 100644 --- a/cmd/uploader.go +++ b/cmd/uploader.go @@ -1,8 +1,10 @@ package cmd import ( + log "log/slog" + "os" + "github.com/minghsu0107/go-random-chat/internal/wire" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -12,7 +14,8 @@ var uploaderCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { server, err := wire.InitializeUploaderServer("uploader") if err != nil { - log.Fatal(err) + log.Error(err.Error()) + os.Exit(1) } server.Serve() }, diff --git a/cmd/user.go b/cmd/user.go index e3ec525..e317d71 100644 --- a/cmd/user.go +++ b/cmd/user.go @@ -1,8 +1,10 @@ package cmd import ( + log "log/slog" + "os" + "github.com/minghsu0107/go-random-chat/internal/wire" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -12,7 +14,8 @@ var userCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { server, err := wire.InitializeUserServer("user") if err != nil { - log.Fatal(err) + log.Error(err.Error()) + os.Exit(1) } server.Serve() }, diff --git a/cmd/web.go b/cmd/web.go index b577093..d940701 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -1,8 +1,10 @@ package cmd import ( + log "log/slog" + "os" + "github.com/minghsu0107/go-random-chat/internal/wire" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -12,7 +14,8 @@ var webCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { server, err := wire.InitializeWebServer("web") if err != nil { - log.Fatal(err) + log.Error(err.Error()) + os.Exit(1) } server.Serve() }, diff --git a/configs/config.example.yaml b/configs/config.example.yaml index f187ef5..09c909a 100644 --- a/configs/config.example.yaml +++ b/configs/config.example.yaml @@ -104,5 +104,3 @@ observability: port: "8080" tracing: jaegerUrl: "http://localhost:14268/api/traces" -logging: - level: error diff --git a/go.mod b/go.mod index 96199a1..ecf7bcf 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/minghsu0107/go-random-chat -go 1.20 +go 1.21 require ( github.com/IBM/sarama v1.42.1 @@ -22,7 +22,6 @@ require ( github.com/prometheus/client_golang v1.16.0 github.com/redis/go-redis/extra/redisotel/v9 v9.0.5 github.com/redis/go-redis/v9 v9.2.0 - github.com/sirupsen/logrus v1.9.3 github.com/slok/go-http-metrics v0.10.0 github.com/sony/gobreaker v0.5.0 github.com/sony/sonyflake v1.1.0 diff --git a/go.sum b/go.sum index 41b31f4..5d260c5 100644 --- a/go.sum +++ b/go.sum @@ -98,8 +98,10 @@ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4Yn github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.9.2 h1:GDaNjuWSGu09guE9Oql0MSTNhNCLlWwO8y/xM5BzcbM= github.com/bytedance/sonic v1.9.2/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= @@ -119,6 +121,7 @@ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGX github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4 h1:/inchEIKaYC1Akx+H+gqO04wryn5h75LSazbRlnya1k= +github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -141,10 +144,13 @@ github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5y github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.10.1 h1:c0g45+xCJhdgFGw7a5QAfdS4byAbud7miNWJ1WwEVf8= +github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= +github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= @@ -152,6 +158,7 @@ github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9 github.com/gin-contrib/cors v1.4.0 h1:oJ6gwtUl3lqV0WEIwM/LxPF1QZ5qe2lGWdY2+bz7y0g= github.com/gin-contrib/cors v1.4.0/go.mod h1:bs9pNM0x/UsmHPBWT2xZz9ROh8xYjYkiURUfmBoMlcs= github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= +github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk= @@ -189,6 +196,7 @@ github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogB github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= @@ -250,6 +258,7 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -338,6 +347,7 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -402,9 +412,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/slok/go-http-metrics v0.10.0 h1:rh0LaYEKza5eaYRGDXujKrOln57nHBi4TtVhmNEpbgM= github.com/slok/go-http-metrics v0.10.0/go.mod h1:lFqdaS4kWMfUKCSukjC47PdCeTk+hXDUVm8kLHRqJ38= github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= @@ -445,6 +454,7 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8= github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= @@ -536,6 +546,7 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -596,6 +607,7 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ= +golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -634,7 +646,6 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/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.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/wire/wire.go b/internal/wire/wire.go index 631ee0a..4c1375d 100644 --- a/internal/wire/wire.go +++ b/internal/wire/wire.go @@ -21,7 +21,7 @@ func InitializeWebServer(name string) (*common.Server, error) { wire.Build( config.NewConfig, common.NewObservabilityInjector, - common.NewHttpLogrus, + common.NewHttpLog, web.NewGinServer, @@ -40,8 +40,8 @@ func InitializeChatServer(name string) (*common.Server, error) { wire.Build( config.NewConfig, common.NewObservabilityInjector, - common.NewHttpLogrus, - common.NewGrpcLogrus, + common.NewHttpLog, + common.NewGrpcLog, infra.NewRedisClient, infra.NewRedisCacheImpl, @@ -106,7 +106,7 @@ func InitializeForwarderServer(name string) (*common.Server, error) { wire.Build( config.NewConfig, common.NewObservabilityInjector, - common.NewGrpcLogrus, + common.NewGrpcLog, infra.NewRedisClient, infra.NewRedisCacheImpl, @@ -139,7 +139,7 @@ func InitializeMatchServer(name string) (*common.Server, error) { wire.Build( config.NewConfig, common.NewObservabilityInjector, - common.NewHttpLogrus, + common.NewHttpLog, infra.NewRedisClient, infra.NewRedisCacheImpl, @@ -185,7 +185,7 @@ func InitializeUploaderServer(name string) (*common.Server, error) { wire.Build( config.NewConfig, common.NewObservabilityInjector, - common.NewHttpLogrus, + common.NewHttpLog, infra.NewRedisClient, @@ -208,8 +208,8 @@ func InitializeUserServer(name string) (*common.Server, error) { wire.Build( config.NewConfig, common.NewObservabilityInjector, - common.NewHttpLogrus, - common.NewGrpcLogrus, + common.NewHttpLog, + common.NewGrpcLog, infra.NewRedisClient, infra.NewRedisCacheImpl, diff --git a/internal/wire/wire_gen.go b/internal/wire/wire_gen.go index 91a704c..9932807 100644 --- a/internal/wire/wire_gen.go +++ b/internal/wire/wire_gen.go @@ -25,12 +25,12 @@ func InitializeWebServer(name string) (*common.Server, error) { if err != nil { return nil, err } - httpLogrus, err := common.NewHttpLogrus(configConfig) + httpLog, err := common.NewHttpLog(configConfig) if err != nil { return nil, err } - engine := web.NewGinServer(name, httpLogrus) - httpServer := web.NewHttpServer(name, httpLogrus, configConfig, engine) + engine := web.NewGinServer(name, httpLog) + httpServer := web.NewHttpServer(name, httpLog, configConfig, engine) router := web.NewRouter(httpServer) infraCloser := web.NewInfraCloser() observabilityInjector := common.NewObservabilityInjector(configConfig) @@ -43,11 +43,11 @@ func InitializeChatServer(name string) (*common.Server, error) { if err != nil { return nil, err } - httpLogrus, err := common.NewHttpLogrus(configConfig) + httpLog, err := common.NewHttpLog(configConfig) if err != nil { return nil, err } - engine := chat.NewGinServer(name, httpLogrus, configConfig) + engine := chat.NewGinServer(name, httpLog, configConfig) melodyChatConn := chat.NewMelodyChatConn(configConfig) router, err := infra.NewBrokerRouter(name) if err != nil { @@ -97,12 +97,12 @@ func InitializeChatServer(name string) (*common.Server, error) { } forwardRepoImpl := chat.NewForwardRepoImpl(forwarderClientConn) forwardServiceImpl := chat.NewForwardServiceImpl(forwardRepoImpl) - httpServer := chat.NewHttpServer(name, httpLogrus, configConfig, engine, melodyChatConn, messageSubscriber, userServiceImpl, messageServiceImpl, channelServiceImpl, forwardServiceImpl) - grpcLogrus, err := common.NewGrpcLogrus(configConfig) + httpServer := chat.NewHttpServer(name, httpLog, configConfig, engine, melodyChatConn, messageSubscriber, userServiceImpl, messageServiceImpl, channelServiceImpl, forwardServiceImpl) + grpcLog, err := common.NewGrpcLog(configConfig) if err != nil { return nil, err } - grpcServer := chat.NewGrpcServer(name, grpcLogrus, configConfig, userServiceImpl, channelServiceImpl) + grpcServer := chat.NewGrpcServer(name, grpcLog, configConfig, userServiceImpl, channelServiceImpl) chatRouter := chat.NewRouter(httpServer, grpcServer) infraCloser := chat.NewInfraCloser() observabilityInjector := common.NewObservabilityInjector(configConfig) @@ -115,7 +115,7 @@ func InitializeForwarderServer(name string) (*common.Server, error) { if err != nil { return nil, err } - grpcLogrus, err := common.NewGrpcLogrus(configConfig) + grpcLog, err := common.NewGrpcLog(configConfig) if err != nil { return nil, err } @@ -142,7 +142,7 @@ func InitializeForwarderServer(name string) (*common.Server, error) { if err != nil { return nil, err } - grpcServer := forwarder.NewGrpcServer(name, grpcLogrus, configConfig, forwardServiceImpl, messageSubscriber) + grpcServer := forwarder.NewGrpcServer(name, grpcLog, configConfig, forwardServiceImpl, messageSubscriber) forwarderRouter := forwarder.NewRouter(grpcServer) infraCloser := forwarder.NewInfraCloser() observabilityInjector := common.NewObservabilityInjector(configConfig) @@ -155,11 +155,11 @@ func InitializeMatchServer(name string) (*common.Server, error) { if err != nil { return nil, err } - httpLogrus, err := common.NewHttpLogrus(configConfig) + httpLog, err := common.NewHttpLog(configConfig) if err != nil { return nil, err } - engine := match.NewGinServer(name, httpLogrus, configConfig) + engine := match.NewGinServer(name, httpLog, configConfig) melodyMatchConn := match.NewMelodyMatchConn() router, err := infra.NewBrokerRouter(name) if err != nil { @@ -195,7 +195,7 @@ func InitializeMatchServer(name string) (*common.Server, error) { matchingRepoImpl := match.NewMatchingRepoImpl(redisCacheImpl, publisher) channelRepoImpl := match.NewChannelRepoImpl(chatClientConn) matchingServiceImpl := match.NewMatchingServiceImpl(matchingRepoImpl, channelRepoImpl) - httpServer := match.NewHttpServer(name, httpLogrus, configConfig, engine, melodyMatchConn, matchSubscriber, userServiceImpl, matchingServiceImpl) + httpServer := match.NewHttpServer(name, httpLog, configConfig, engine, melodyMatchConn, matchSubscriber, userServiceImpl, matchingServiceImpl) matchRouter := match.NewRouter(httpServer) infraCloser := match.NewInfraCloser() observabilityInjector := common.NewObservabilityInjector(configConfig) @@ -208,17 +208,17 @@ func InitializeUploaderServer(name string) (*common.Server, error) { if err != nil { return nil, err } - httpLogrus, err := common.NewHttpLogrus(configConfig) + httpLog, err := common.NewHttpLog(configConfig) if err != nil { return nil, err } - engine := uploader.NewGinServer(name, httpLogrus, configConfig) + engine := uploader.NewGinServer(name, httpLog, configConfig) universalClient, err := infra.NewRedisClient(configConfig) if err != nil { return nil, err } channelUploadRateLimiter := uploader.NewChannelUploadRateLimiter(universalClient, configConfig) - httpServer := uploader.NewHttpServer(name, httpLogrus, configConfig, engine, channelUploadRateLimiter) + httpServer := uploader.NewHttpServer(name, httpLog, configConfig, engine, channelUploadRateLimiter) router := uploader.NewRouter(httpServer) infraCloser := uploader.NewInfraCloser() observabilityInjector := common.NewObservabilityInjector(configConfig) @@ -231,11 +231,11 @@ func InitializeUserServer(name string) (*common.Server, error) { if err != nil { return nil, err } - httpLogrus, err := common.NewHttpLogrus(configConfig) + httpLog, err := common.NewHttpLog(configConfig) if err != nil { return nil, err } - engine := user.NewGinServer(name, httpLogrus, configConfig) + engine := user.NewGinServer(name, httpLog, configConfig) universalClient, err := infra.NewRedisClient(configConfig) if err != nil { return nil, err @@ -247,12 +247,12 @@ func InitializeUserServer(name string) (*common.Server, error) { return nil, err } userServiceImpl := user.NewUserServiceImpl(userRepoImpl, idGenerator) - httpServer := user.NewHttpServer(name, httpLogrus, configConfig, engine, userServiceImpl) - grpcLogrus, err := common.NewGrpcLogrus(configConfig) + httpServer := user.NewHttpServer(name, httpLog, configConfig, engine, userServiceImpl) + grpcLog, err := common.NewGrpcLog(configConfig) if err != nil { return nil, err } - grpcServer := user.NewGrpcServer(name, grpcLogrus, configConfig, userServiceImpl) + grpcServer := user.NewGrpcServer(name, grpcLog, configConfig, userServiceImpl) router := user.NewRouter(httpServer, grpcServer) infraCloser := user.NewInfraCloser() observabilityInjector := common.NewObservabilityInjector(configConfig) diff --git a/pkg/chat/grpc.go b/pkg/chat/grpc.go index 5ad4184..43ef0fa 100644 --- a/pkg/chat/grpc.go +++ b/pkg/chat/grpc.go @@ -1,7 +1,9 @@ package chat import ( + "log/slog" "net" + "os" "google.golang.org/grpc" @@ -13,13 +15,13 @@ import ( type GrpcServer struct { grpcPort string - logger common.GrpcLogrus + logger common.GrpcLog s *grpc.Server userSvc UserService chanSvc ChannelService } -func NewGrpcServer(name string, logger common.GrpcLogrus, config *config.Config, userSvc UserService, chanSvc ChannelService) *GrpcServer { +func NewGrpcServer(name string, logger common.GrpcLog, config *config.Config, userSvc UserService, chanSvc ChannelService) *GrpcServer { srv := &GrpcServer{ grpcPort: config.Chat.Grpc.Server.Port, logger: logger, @@ -38,13 +40,15 @@ func (srv *GrpcServer) Register() { func (srv *GrpcServer) Run() { go func() { addr := "0.0.0.0:" + srv.grpcPort - srv.logger.Infoln("grpc server listening on ", addr) + srv.logger.Info("grpc server listening", slog.String("addr", addr)) lis, err := net.Listen("tcp", addr) if err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } if err := srv.s.Serve(lis); err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/chat/grpc_rpc.go b/pkg/chat/grpc_rpc.go index 2838e37..405f1bc 100644 --- a/pkg/chat/grpc_rpc.go +++ b/pkg/chat/grpc_rpc.go @@ -11,7 +11,7 @@ import ( func (srv *GrpcServer) CreateChannel(ctx context.Context, req *chatpb.CreateChannelRequest) (*chatpb.CreateChannelResponse, error) { channel, err := srv.chanSvc.CreateChannel(ctx) if err != nil { - srv.logger.Error(err) + srv.logger.Error(err.Error()) return nil, status.Error(codes.Internal, err.Error()) } return &chatpb.CreateChannelResponse{ @@ -22,7 +22,7 @@ func (srv *GrpcServer) CreateChannel(ctx context.Context, req *chatpb.CreateChan func (srv *GrpcServer) AddUserToChannel(ctx context.Context, req *chatpb.AddUserRequest) (*chatpb.AddUserResponse, error) { if err := srv.userSvc.AddUserToChannel(ctx, req.ChannelId, req.UserId); err != nil { - srv.logger.Error(err) + srv.logger.Error(err.Error()) return nil, status.Error(codes.Internal, err.Error()) } return &chatpb.AddUserResponse{}, nil diff --git a/pkg/chat/http.go b/pkg/chat/http.go index 19b0607..b269106 100644 --- a/pkg/chat/http.go +++ b/pkg/chat/http.go @@ -2,7 +2,9 @@ package chat import ( "context" + "log/slog" "net/http" + "os" "github.com/gin-gonic/gin" "github.com/minghsu0107/go-random-chat/pkg/common" @@ -29,7 +31,7 @@ type MelodyChatConn struct { type HttpServer struct { name string - logger common.HttpLogrus + logger common.HttpLog svr *gin.Engine mc MelodyChatConn httpPort string @@ -51,7 +53,7 @@ func NewMelodyChatConn(config *config.Config) MelodyChatConn { return MelodyChat } -func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) *gin.Engine { +func NewGinServer(name string, logger common.HttpLog, config *config.Config) *gin.Engine { svr := gin.New() svr.Use(gin.Recovery()) svr.Use(common.CorsMiddleware()) @@ -67,7 +69,7 @@ func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) return svr } -func NewHttpServer(name string, logger common.HttpLogrus, config *config.Config, svr *gin.Engine, mc MelodyChatConn, msgSubscriber *MessageSubscriber, userSvc UserService, msgSvc MessageService, chanSvc ChannelService, forwardSvc ForwardService) *HttpServer { +func NewHttpServer(name string, logger common.HttpLog, config *config.Config, svr *gin.Engine, mc MelodyChatConn, msgSubscriber *MessageSubscriber, userSvc UserService, msgSvc MessageService, chanSvc ChannelService, forwardSvc ForwardService) *HttpServer { initJWT(config) return &HttpServer{ @@ -140,16 +142,18 @@ func (r *HttpServer) Run() { Addr: addr, Handler: common.NewOtelHttpHandler(r.svr, r.name+"_http"), } - r.logger.Infoln("http server listening on ", addr) + r.logger.Info("http server listening", slog.String("addr", addr)) err := r.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() go func() { err := r.msgSubscriber.Run() if err != nil { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/chat/http_api.go b/pkg/chat/http_api.go index 841ae74..610c658 100644 --- a/pkg/chat/http_api.go +++ b/pkg/chat/http_api.go @@ -35,7 +35,7 @@ func (r *HttpServer) StartChat(c *gin.Context) { response(c, http.StatusNotFound, ErrUserNotFound) return } - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -49,13 +49,13 @@ func (r *HttpServer) StartChat(c *gin.Context) { return } if authResult.Expired { - r.logger.Error(common.ErrTokenExpired) + r.logger.Error(common.ErrTokenExpired.Error()) response(c, http.StatusUnauthorized, common.ErrTokenExpired) } channelID := authResult.ChannelID exist, err := r.userSvc.IsChannelUserExist(c.Request.Context(), channelID, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -65,7 +65,7 @@ func (r *HttpServer) StartChat(c *gin.Context) { } if err := r.mc.HandleRequest(c.Writer, c.Request); err != nil { - r.logger.Errorf("upgrade websocket error: %v", err) + r.logger.Error("upgrade websocket error: " + err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -109,7 +109,7 @@ func (r *HttpServer) GetChannelUsers(c *gin.Context) { } userIDs, err := r.userSvc.GetChannelUserIDs(c.Request.Context(), channelID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -140,7 +140,7 @@ func (r *HttpServer) GetOnlineUsers(c *gin.Context) { } userIDs, err := r.userSvc.GetOnlineUserIDs(c.Request.Context(), channelID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -173,7 +173,7 @@ func (r *HttpServer) ListMessages(c *gin.Context) { pageState := c.Query("ps") msgs, nextPageState, err := r.msgSvc.ListMessages(c.Request.Context(), channelID, pageState) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -214,7 +214,7 @@ func (r *HttpServer) DeleteChannel(c *gin.Context) { exist, err := r.userSvc.IsChannelUserExist(c.Request.Context(), channelID, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -225,13 +225,13 @@ func (r *HttpServer) DeleteChannel(c *gin.Context) { err = r.msgSvc.BroadcastActionMessage(c.Request.Context(), channelID, userID, LeavedMessage) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } err = r.chanSvc.DeleteChannel(c.Request.Context(), channelID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -243,7 +243,7 @@ func (r *HttpServer) DeleteChannel(c *gin.Context) { func (r *HttpServer) HandleChatOnConnect(sess *melody.Session) { userID, err := strconv.ParseUint(sess.Request.URL.Query().Get("uid"), 10, 64) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } accessToken := sess.Request.URL.Query().Get("access_token") @@ -251,19 +251,19 @@ func (r *HttpServer) HandleChatOnConnect(sess *melody.Session) { AccessToken: accessToken, }) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) } if authResult.Expired { - r.logger.Error(common.ErrTokenExpired) + r.logger.Error(common.ErrTokenExpired.Error()) } channelID := authResult.ChannelID err = r.initializeChatSession(sess, channelID, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } if err := r.msgSvc.BroadcastConnectMessage(context.Background(), channelID, userID); err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } } @@ -283,45 +283,45 @@ func (r *HttpServer) initializeChatSession(sess *melody.Session, channelID, user func (r *HttpServer) HandleChatOnMessage(sess *melody.Session, data []byte) { msgPresenter, err := DecodeToMessagePresenter(data) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } msg, err := msgPresenter.ToMessage(sess.Request.URL.Query().Get("access_token")) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } switch msg.Event { case EventText: if err := r.msgSvc.BroadcastTextMessage(context.Background(), msg.ChannelID, msg.UserID, msg.Payload); err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) } case EventAction: if err := r.msgSvc.BroadcastActionMessage(context.Background(), msg.ChannelID, msg.UserID, Action(msg.Payload)); err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) } case EventSeen: messageID, err := strconv.ParseUint(msg.Payload, 10, 64) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } if err := r.msgSvc.MarkMessageSeen(context.Background(), msg.ChannelID, msg.UserID, messageID); err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) } case EventFile: if err := r.msgSvc.BroadcastFileMessage(context.Background(), msg.ChannelID, msg.UserID, msg.Payload); err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) } default: - r.logger.Errorf("invailid event type: %v", msg.Event) + r.logger.Error("invailid event type: " + strconv.Itoa(msg.Event)) } } func (r *HttpServer) HandleChatOnClose(sess *melody.Session, i int, s string) error { userID, err := strconv.ParseUint(sess.Request.URL.Query().Get("uid"), 10, 64) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return err } accessToken := sess.Request.URL.Query().Get("access_token") @@ -329,22 +329,22 @@ func (r *HttpServer) HandleChatOnClose(sess *melody.Session, i int, s string) er AccessToken: accessToken, }) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return err } if authResult.Expired { - r.logger.Error(common.ErrTokenExpired) + r.logger.Error(common.ErrTokenExpired.Error()) return common.ErrTokenExpired } channelID := authResult.ChannelID err = r.userSvc.DeleteOnlineUser(context.Background(), channelID, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return err } err = r.forwardSvc.RemoveChannelSession(context.Background(), channelID, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return err } return r.msgSvc.BroadcastActionMessage(context.Background(), channelID, userID, OfflineMessage) diff --git a/pkg/common/http_middleware.go b/pkg/common/http_middleware.go index d34cc0f..2e2f0ae 100644 --- a/pkg/common/http_middleware.go +++ b/pkg/common/http_middleware.go @@ -2,6 +2,7 @@ package common import ( "context" + "log/slog" "net/http" "strconv" "strings" @@ -9,7 +10,6 @@ import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" - "github.com/sirupsen/logrus" ) type HTTPContextKey string @@ -45,7 +45,7 @@ func CorsMiddleware() gin.HandlerFunc { return cors.New(config) } -func LoggingMiddleware(logger HttpLogrus) gin.HandlerFunc { +func LoggingMiddleware(logger HttpLog) gin.HandlerFunc { return func(c *gin.Context) { // Start timer start := time.Now() @@ -56,19 +56,19 @@ func LoggingMiddleware(logger HttpLogrus) gin.HandlerFunc { // Stop timer duration := getDurationInMillseconds(start) - entry := logger.WithFields(logrus.Fields{ - "duration_ms": duration, - "method": c.Request.Method, - "path": c.Request.RequestURI, - "status": c.Writer.Status(), - "referrer": c.Request.Referer(), - "trace_id": getTraceID(c), - }) + attrs := []slog.Attr{ + slog.Float64("duration_ms", duration), + slog.String("method", c.Request.Method), + slog.String("path", c.Request.RequestURI), + slog.Int("status", c.Writer.Status()), + slog.String("referrer", c.Request.Referer()), + slog.String("trace_id", getTraceID(c)), + } if c.Writer.Status() >= 500 { - entry.Error(c.Errors.String()) + logger.Error(c.Errors.String(), attrs) } else { - entry.Info("") + logger.Info("", attrs) } } } diff --git a/pkg/common/log.go b/pkg/common/log.go index c093272..daedfba 100644 --- a/pkg/common/log.go +++ b/pkg/common/log.go @@ -4,45 +4,49 @@ import ( "io" "os" + "log/slog" + "github.com/gin-gonic/gin" "github.com/minghsu0107/go-random-chat/pkg/config" - log "github.com/sirupsen/logrus" ) -type HttpLogrus struct { - *log.Entry +type HttpLog struct { + *slog.Logger } -type GrpcLogrus struct { - *log.Entry +type GrpcLog struct { + *slog.Logger } -func NewHttpLogrus(config *config.Config) (HttpLogrus, error) { - gin.SetMode(gin.ReleaseMode) - gin.DefaultWriter = io.Writer(os.Stderr) - - if err := initLogging(config); err != nil { - return HttpLogrus{}, err - } - - return HttpLogrus{log.WithField("protocol", "http")}, nil +func init() { + slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: slog.LevelError, + AddSource: false, + }))) } -func NewGrpcLogrus(config *config.Config) (GrpcLogrus, error) { - if err := initLogging(config); err != nil { - return GrpcLogrus{}, err - } +func NewHttpLog(config *config.Config) (HttpLog, error) { + logHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: slog.LevelError, + AddSource: false, + }).WithAttrs([]slog.Attr{ + slog.String("proto", "http"), + }) + logger := slog.New(logHandler) + + gin.SetMode(gin.ReleaseMode) + gin.DefaultWriter = io.Writer(os.Stderr) - return GrpcLogrus{log.WithField("protocol", "grpc")}, nil + return HttpLog{logger}, nil } -func initLogging(config *config.Config) error { - logrusLevel, err := log.ParseLevel(config.Logging.Level) - if err != nil { - return err - } - log.SetOutput(os.Stderr) - log.SetLevel(logrusLevel) - log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableColors: true}) +func NewGrpcLog(config *config.Config) (GrpcLog, error) { + logHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: slog.LevelError, + AddSource: false, + }).WithAttrs([]slog.Attr{ + slog.String("proto", "grpc"), + }) + logger := slog.New(logHandler) - return nil + return GrpcLog{logger}, nil } diff --git a/pkg/common/observability.go b/pkg/common/observability.go index 0cc34b5..771a12c 100644 --- a/pkg/common/observability.go +++ b/pkg/common/observability.go @@ -2,12 +2,13 @@ package common import ( "fmt" + "log/slog" "net/http" + "os" "github.com/minghsu0107/go-random-chat/pkg/config" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" - log "github.com/sirupsen/logrus" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" propjaeger "go.opentelemetry.io/contrib/propagators/jaeger" "go.opentelemetry.io/otel" @@ -54,10 +55,11 @@ func (injector *ObservabilityInjector) Register(service string) error { }, )) promHttpSrv.Handler = m - log.Infof("starting prom metrics on :%s", injector.promPort) + slog.Info("starting prom metrics on :" + injector.promPort) err := promHttpSrv.ListenAndServe() if err != nil { - log.Fatal(err) + slog.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/common/server.go b/pkg/common/server.go index ad8f4fa..93afe28 100644 --- a/pkg/common/server.go +++ b/pkg/common/server.go @@ -2,12 +2,11 @@ package common import ( "context" + "log/slog" "os" "os/signal" "syscall" "time" - - log "github.com/sirupsen/logrus" ) type HttpServer interface { @@ -44,7 +43,8 @@ func NewServer(name string, router Router, infraCloser InfraCloser, obsInjector func (s *Server) Serve() { if err := s.obsInjector.Register(s.name); err != nil { - log.Fatal(err) + slog.Error(err.Error()) + os.Exit(1) } s.router.Run() @@ -65,20 +65,20 @@ func (s *Server) Serve() { func (s *Server) GracefulStop(ctx context.Context, done chan bool) { err := s.router.GracefulStop(ctx) if err != nil { - log.Error(err) + slog.Error(err.Error()) } if TracerProvider != nil { err = TracerProvider.Shutdown(ctx) if err != nil { - log.Error(err) + slog.Error(err.Error()) } } if err = s.infraCloser.Close(); err != nil { - log.Error(err) + slog.Error(err.Error()) } - log.Info("gracefully shutdowned") + slog.Info("gracefully shutdowned") done <- true } diff --git a/pkg/config/config.go b/pkg/config/config.go index 2d20305..b983bbc 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -17,7 +17,6 @@ type Config struct { Cassandra *CassandraConfig `mapstructure:"cassandra"` Redis *RedisConfig `mapstructure:"redis"` Observability *ObservabilityConfig `mapstructure:"observability"` - Logging *LoggingConfig `mapstructure:"logging"` } type WebConfig struct { @@ -182,10 +181,6 @@ type ObservabilityConfig struct { } } -type LoggingConfig struct { - Level string -} - func setDefault() { viper.SetDefault("web.http.server.port", "5000") @@ -256,8 +251,6 @@ func setDefault() { viper.SetDefault("observability.prometheus.port", "8080") viper.SetDefault("observability.tracing.jaegerUrl", "") - - viper.SetDefault("logging.level", "info") } func NewConfig() (*Config, error) { diff --git a/pkg/forwarder/grpc.go b/pkg/forwarder/grpc.go index a9b3e60..223865d 100644 --- a/pkg/forwarder/grpc.go +++ b/pkg/forwarder/grpc.go @@ -2,9 +2,12 @@ package forwarder import ( "net" + "os" "google.golang.org/grpc" + "log/slog" + "github.com/minghsu0107/go-random-chat/pkg/common" "github.com/minghsu0107/go-random-chat/pkg/config" "github.com/minghsu0107/go-random-chat/pkg/transport" @@ -13,13 +16,13 @@ import ( type GrpcServer struct { grpcPort string - logger common.GrpcLogrus + logger common.GrpcLog s *grpc.Server forwardSvc ForwardService msgSubscriber *MessageSubscriber } -func NewGrpcServer(name string, logger common.GrpcLogrus, config *config.Config, forwardSvc ForwardService, msgSubscriber *MessageSubscriber) *GrpcServer { +func NewGrpcServer(name string, logger common.GrpcLog, config *config.Config, forwardSvc ForwardService, msgSubscriber *MessageSubscriber) *GrpcServer { srv := &GrpcServer{ grpcPort: config.Forwarder.Grpc.Server.Port, logger: logger, @@ -39,19 +42,22 @@ func (srv *GrpcServer) Register() { func (srv *GrpcServer) Run() { go func() { addr := "0.0.0.0:" + srv.grpcPort - srv.logger.Infoln("grpc server listening on ", addr) + srv.logger.Info("grpc server listening", slog.String("addr", addr)) lis, err := net.Listen("tcp", addr) if err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } if err := srv.s.Serve(lis); err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } }() go func() { err := srv.msgSubscriber.Run() if err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/forwarder/grpc_rpc.go b/pkg/forwarder/grpc_rpc.go index 0741e0c..a7ec13a 100644 --- a/pkg/forwarder/grpc_rpc.go +++ b/pkg/forwarder/grpc_rpc.go @@ -10,7 +10,7 @@ import ( func (srv *GrpcServer) RegisterChannelSession(ctx context.Context, req *forwarderpb.RegisterChannelSessionRequest) (*forwarderpb.RegisterChannelSessionResponse, error) { if err := srv.forwardSvc.RegisterChannelSession(ctx, req.ChannelId, req.UserId, req.Subscriber); err != nil { - srv.logger.Error(err) + srv.logger.Error(err.Error()) return nil, status.Error(codes.Internal, err.Error()) } return &forwarderpb.RegisterChannelSessionResponse{}, nil @@ -18,7 +18,7 @@ func (srv *GrpcServer) RegisterChannelSession(ctx context.Context, req *forwarde func (srv *GrpcServer) RemoveChannelSession(ctx context.Context, req *forwarderpb.RemoveChannelSessionRequest) (*forwarderpb.RemoveChannelSessionResponse, error) { if err := srv.forwardSvc.RemoveChannelSession(ctx, req.ChannelId, req.UserId); err != nil { - srv.logger.Error(err) + srv.logger.Error(err.Error()) return nil, status.Error(codes.Internal, err.Error()) } return &forwarderpb.RemoveChannelSessionResponse{}, nil diff --git a/pkg/match/http.go b/pkg/match/http.go index b8cb043..49143e3 100644 --- a/pkg/match/http.go +++ b/pkg/match/http.go @@ -2,7 +2,9 @@ package match import ( "context" + "log/slog" "net/http" + "os" "github.com/gin-gonic/gin" "github.com/minghsu0107/go-random-chat/pkg/common" @@ -29,7 +31,7 @@ type MelodyMatchConn struct { type HttpServer struct { name string - logger common.HttpLogrus + logger common.HttpLog svr *gin.Engine mm MelodyMatchConn httpPort string @@ -47,7 +49,7 @@ func NewMelodyMatchConn() MelodyMatchConn { return MelodyMatch } -func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) *gin.Engine { +func NewGinServer(name string, logger common.HttpLog, config *config.Config) *gin.Engine { svr := gin.New() svr.Use(gin.Recovery()) svr.Use(common.CorsMiddleware()) @@ -63,7 +65,7 @@ func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) return svr } -func NewHttpServer(name string, logger common.HttpLogrus, config *config.Config, svr *gin.Engine, mm MelodyMatchConn, matchSubscriber *MatchSubscriber, userSvc UserService, matchSvc MatchingService) *HttpServer { +func NewHttpServer(name string, logger common.HttpLog, config *config.Config, svr *gin.Engine, mm MelodyMatchConn, matchSubscriber *MatchSubscriber, userSvc UserService, matchSvc MatchingService) *HttpServer { return &HttpServer{ name: name, logger: logger, @@ -127,16 +129,18 @@ func (r *HttpServer) Run() { Addr: addr, Handler: common.NewOtelHttpHandler(r.svr, r.name+"_http"), } - r.logger.Infoln("http server listening on ", addr) + r.logger.Info("http server listening", slog.String("addr", addr)) err := r.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() go func() { err := r.matchSubscriber.Run() if err != nil { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/match/http_api.go b/pkg/match/http_api.go index 843b43b..6d37dc8 100644 --- a/pkg/match/http_api.go +++ b/pkg/match/http_api.go @@ -31,12 +31,12 @@ func (r *HttpServer) Match(c *gin.Context) { response(c, http.StatusNotFound, ErrUserNotFound) return } - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } if err := r.mm.HandleRequest(c.Writer, c.Request); err != nil { - r.logger.Errorf("upgrade websocket error: %v", err) + r.logger.Error("upgrade websocket error: " + err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -50,20 +50,20 @@ func (r *HttpServer) HandleMatchOnConnect(sess *melody.Session) { } err := r.initializeMatchSession(sess, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } ctx := context.Background() matchResult, err := r.matchSvc.Match(ctx, userID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } if !matchResult.Matched { return } if err := r.matchSvc.BroadcastMatchResult(ctx, matchResult); err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) return } } diff --git a/pkg/match/match_sub.go b/pkg/match/match_sub.go index ca5b9f1..f0328ef 100644 --- a/pkg/match/match_sub.go +++ b/pkg/match/match_sub.go @@ -2,9 +2,9 @@ package match import ( "context" + "log/slog" "github.com/ThreeDotsLabs/watermill/message" - log "github.com/sirupsen/logrus" "gopkg.in/olahol/melody.v1" ) @@ -58,7 +58,7 @@ func (s *MatchSubscriber) sendMatchResult(ctx context.Context, result *MatchResu userID := uid.(uint64) if (userID == result.PeerID) || (userID == result.UserID) { if err := s.userSvc.AddUserToChannel(ctx, result.ChannelID, userID); err != nil { - log.Error(err) + slog.Error(err.Error()) return false } return true diff --git a/pkg/transport/grpc.go b/pkg/transport/grpc.go index 26bfeb0..8d33852 100644 --- a/pkg/transport/grpc.go +++ b/pkg/transport/grpc.go @@ -3,6 +3,7 @@ package transport import ( "context" "fmt" + "log/slog" "runtime/debug" "time" @@ -20,7 +21,6 @@ import ( "github.com/minghsu0107/go-random-chat/pkg/common" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - log "github.com/sirupsen/logrus" "github.com/sony/gobreaker" "go.opentelemetry.io/otel/trace" "google.golang.org/grpc" @@ -34,31 +34,24 @@ var ( ServiceIdHeader string = "Service-Id" ) -func interceptorLogger(l log.FieldLogger) logging.Logger { +func interceptorLogger(l common.GrpcLog) logging.Logger { return logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) { - f := make(map[string]any, len(fields)/2) - i := logging.Fields(fields).Iterator() - for i.Next() { - k, v := i.At() - f[k] = v - } - switch lvl { case logging.LevelDebug: - l.WithFields(f).Debug(msg) + l.Debug(msg, fields...) case logging.LevelInfo: - l.WithFields(f).Info(msg) + l.Info(msg, fields...) case logging.LevelWarn: - l.WithFields(f).Warn(msg) + l.Warn(msg, fields...) case logging.LevelError: - l.WithFields(f).Error(msg) + l.Error(msg, fields...) default: panic(fmt.Sprintf("unknown level %v", lvl)) } }) } -func InitializeGrpcServer(name string, logger common.GrpcLogrus) *grpc.Server { +func InitializeGrpcServer(name string, logger common.GrpcLog) *grpc.Server { opts := []grpc.ServerOption{ grpc.MaxRecvMsgSize(1024 * 1024 * 8), // increase to 8 MB (default: 4 MB) grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ @@ -102,7 +95,7 @@ func InitializeGrpcServer(name string, logger common.GrpcLogrus) *grpc.Server { }) grpcPanicRecoveryHandler := func(p any) (err error) { panicsTotal.Inc() - logger.Errorf("recovered from panic, stack: %s", string(debug.Stack())) + logger.Error("recovered from panic, stack: " + string(debug.Stack())) return status.Errorf(codes.Internal, "%s", p) } logTraceID := func(ctx context.Context) logging.Fields { @@ -175,7 +168,7 @@ func InitializeGrpcClient(svcHost string) (*grpc.ClientConn, error) { //grpc.WithBlock(), ) - log.Infof("connecting to grpc host: %s", svcHost) + slog.Info("connecting to grpc host: " + svcHost) conn, err := grpc.DialContext( ctx, fmt.Sprintf("%s:///%s", scheme, svcHost), diff --git a/pkg/uploader/http.go b/pkg/uploader/http.go index 3cac9de..72149b8 100644 --- a/pkg/uploader/http.go +++ b/pkg/uploader/http.go @@ -3,9 +3,12 @@ package uploader import ( "context" "net/http" + "os" "strconv" "time" + "log/slog" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" @@ -40,7 +43,7 @@ func NewChannelUploadRateLimiter(rc redis.UniversalClient, config *config.Config type HttpServer struct { name string - logger common.HttpLogrus + logger common.HttpLog svr *gin.Engine s3Endpoint string s3Bucket string @@ -53,7 +56,7 @@ type HttpServer struct { serveSwag bool } -func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) *gin.Engine { +func NewGinServer(name string, logger common.HttpLog, config *config.Config) *gin.Engine { svr := gin.New() svr.Use(gin.Recovery()) svr.Use(common.CorsMiddleware()) @@ -69,7 +72,7 @@ func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) return svr } -func NewHttpServer(name string, logger common.HttpLogrus, config *config.Config, svr *gin.Engine, channelUploadRateLimiter ChannelUploadRateLimiter) *HttpServer { +func NewHttpServer(name string, logger common.HttpLog, config *config.Config, svr *gin.Engine, channelUploadRateLimiter ChannelUploadRateLimiter) *HttpServer { s3Endpoint := config.Uploader.S3.Endpoint s3Bucket := config.Uploader.S3.Bucket creds := credentials.NewStaticCredentialsProvider(config.Uploader.S3.AccessKey, config.Uploader.S3.SecretKey, "") @@ -113,7 +116,7 @@ func (r *HttpServer) ChannelUploadRateLimit() gin.HandlerFunc { } allow, err := r.channelUploadRateLimiter.Allow(c.Request.Context(), strconv.FormatUint(channelID, 10)) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) c.AbortWithStatus(http.StatusInternalServerError) return } @@ -161,10 +164,11 @@ func (r *HttpServer) Run() { Addr: addr, Handler: common.NewOtelHttpHandler(r.svr, r.name+"_http"), } - r.logger.Infoln("http server listening on ", addr) + r.logger.Info("http server listening", slog.String("addr", addr)) err := r.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/uploader/http_api.go b/pkg/uploader/http_api.go index 9d00d05..ac0733e 100644 --- a/pkg/uploader/http_api.go +++ b/pkg/uploader/http_api.go @@ -33,13 +33,13 @@ func (r *HttpServer) UploadFiles(c *gin.Context) { return } if err := c.Request.ParseMultipartForm(r.maxMemory); err != nil { - r.logger.Errorf("error parsing multipart form into memory: %v", err) + r.logger.Error("error parsing multipart form into memory: " + err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } form, err := c.MultipartForm() if err != nil { - r.logger.Errorf("parse multipart form error: %v", err) + r.logger.Error("parse multipart form error: " + err.Error()) response(c, http.StatusBadRequest, ErrReceiveFile) return } @@ -50,7 +50,7 @@ func (r *HttpServer) UploadFiles(c *gin.Context) { for _, fileHeader := range fileHeaders { f, err := fileHeader.Open() if err != nil { - r.logger.Errorf("error opening multipart file header: %v", err) + r.logger.Error("error opening multipart file header: " + err.Error()) response(c, http.StatusBadRequest, ErrOpenFile) return } @@ -58,7 +58,7 @@ func (r *HttpServer) UploadFiles(c *gin.Context) { extension := filepath.Ext(fileHeader.Filename) newFileName := newObjectKey(channelID, extension) if err := r.putFileToS3(c.Request.Context(), r.s3Bucket, newFileName, f); err != nil { - r.logger.Errorf("error putting file to S3: %v", err) + r.logger.Error("error putting file to S3: ", err.Error()) response(c, http.StatusInternalServerError, ErrUploadFile) return } @@ -111,7 +111,7 @@ func (r *HttpServer) GetPresignedUpload(c *gin.Context) { objectKey := newObjectKey(channelID, common.Join(".", req.Extension)) res, err := r.presigner.PutObject(c.Request.Context(), r.s3Bucket, objectKey) if err != nil { - r.logger.Errorf("get presigned upload url failed: %v", err) + r.logger.Error("get presigned upload url failed: " + err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -162,7 +162,7 @@ func (r *HttpServer) GetPresignedDownload(c *gin.Context) { res, err := r.presigner.GetObject(c.Request.Context(), r.s3Bucket, objectKey) if err != nil { - r.logger.Errorf("get presigned download url failed: %v", err) + r.logger.Error("get presigned download url failed: " + err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } diff --git a/pkg/user/grpc.go b/pkg/user/grpc.go index 4c6b8a1..95adc2a 100644 --- a/pkg/user/grpc.go +++ b/pkg/user/grpc.go @@ -1,7 +1,9 @@ package user import ( + "log/slog" "net" + "os" "google.golang.org/grpc" @@ -13,12 +15,12 @@ import ( type GrpcServer struct { grpcPort string - logger common.GrpcLogrus + logger common.GrpcLog s *grpc.Server userSvc UserService } -func NewGrpcServer(name string, logger common.GrpcLogrus, config *config.Config, userSvc UserService) *GrpcServer { +func NewGrpcServer(name string, logger common.GrpcLog, config *config.Config, userSvc UserService) *GrpcServer { srv := &GrpcServer{ grpcPort: config.User.Grpc.Server.Port, logger: logger, @@ -35,13 +37,15 @@ func (srv *GrpcServer) Register() { func (srv *GrpcServer) Run() { go func() { addr := "0.0.0.0:" + srv.grpcPort - srv.logger.Infoln("grpc server listening on ", addr) + srv.logger.Info("grpc server listening", slog.String("addr", addr)) lis, err := net.Listen("tcp", addr) if err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } if err := srv.s.Serve(lis); err != nil { - srv.logger.Fatal(err) + srv.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/user/grpc_rpc.go b/pkg/user/grpc_rpc.go index aa988e1..5b989b6 100644 --- a/pkg/user/grpc_rpc.go +++ b/pkg/user/grpc_rpc.go @@ -17,7 +17,7 @@ func (srv *GrpcServer) GetUser(ctx context.Context, req *userpb.GetUserRequest) Exist: false, }, nil } - srv.logger.Error(err) + srv.logger.Error(err.Error()) return nil, status.Error(codes.Unavailable, err.Error()) } return &userpb.GetUserResponse{ @@ -35,7 +35,7 @@ func (srv *GrpcServer) GetUserIdBySession(ctx context.Context, req *userpb.GetUs if errors.Is(err, ErrSessionNotFound) { return nil, status.Error(codes.NotFound, err.Error()) } - srv.logger.Error(err) + srv.logger.Error(err.Error()) return nil, status.Error(codes.Unavailable, err.Error()) } return &userpb.GetUserIdBySessionResponse{ diff --git a/pkg/user/http.go b/pkg/user/http.go index ab5cdd9..e511f19 100644 --- a/pkg/user/http.go +++ b/pkg/user/http.go @@ -2,7 +2,9 @@ package user import ( "context" + "log/slog" "net/http" + "os" "strings" "github.com/gin-gonic/gin" @@ -21,7 +23,7 @@ import ( type HttpServer struct { name string - logger common.HttpLogrus + logger common.HttpLog svr *gin.Engine httpPort string httpServer *http.Server @@ -32,7 +34,7 @@ type HttpServer struct { authCookieConfig config.CookieConfig } -func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) *gin.Engine { +func NewGinServer(name string, logger common.HttpLog, config *config.Config) *gin.Engine { svr := gin.New() svr.Use(gin.Recovery()) svr.Use(common.CorsMiddleware()) @@ -47,7 +49,7 @@ func NewGinServer(name string, logger common.HttpLogrus, config *config.Config) return svr } -func NewHttpServer(name string, logger common.HttpLogrus, config *config.Config, svr *gin.Engine, userSvc UserService) *HttpServer { +func NewHttpServer(name string, logger common.HttpLog, config *config.Config, svr *gin.Engine, userSvc UserService) *HttpServer { return &HttpServer{ name: name, logger: logger, @@ -117,10 +119,11 @@ func (r *HttpServer) Run() { Addr: addr, Handler: common.NewOtelHttpHandler(r.svr, r.name+"_http"), } - r.logger.Infoln("http server listening on ", addr) + r.logger.Info("http server listening", slog.String("addr", addr)) err := r.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() } diff --git a/pkg/user/http_api.go b/pkg/user/http_api.go index 4e414e8..e7295ed 100644 --- a/pkg/user/http_api.go +++ b/pkg/user/http_api.go @@ -29,13 +29,13 @@ func (r *HttpServer) CreateLocalUser(c *gin.Context) { AuthType: LocalAuth, }) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } sid, err := r.userSvc.SetUserSession(c.Request.Context(), user.ID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -81,7 +81,7 @@ func (r *HttpServer) GetUser(c *gin.Context) { response(c, http.StatusNotFound, ErrUserNotFound) return } - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -114,7 +114,7 @@ func (r *HttpServer) GetUserMe(c *gin.Context) { response(c, http.StatusNotFound, ErrUserNotFound) return } - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -133,7 +133,7 @@ func (r *HttpServer) GetUserMe(c *gin.Context) { func (r *HttpServer) OAuthGoogleLogin(c *gin.Context) { oauthState, err := common.GenerateStateOauthCookie(c, r.oauthCookieConfig.MaxAge, r.oauthCookieConfig.Path, r.oauthCookieConfig.Domain) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } @@ -150,7 +150,7 @@ func (r *HttpServer) OAuthGoogleLogin(c *gin.Context) { func (r *HttpServer) OAuthGoogleCallback(c *gin.Context) { oauthState, err := common.GetCookie(c, common.OAuthStateCookieName) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) c.Redirect(http.StatusTemporaryRedirect, "/") return } @@ -162,13 +162,13 @@ func (r *HttpServer) OAuthGoogleCallback(c *gin.Context) { token, err := r.googleOauthConfig.Exchange(c.Request.Context(), c.Request.FormValue("code")) if err != nil { - r.logger.Errorf("code exchange wrong: %v", err) + r.logger.Error("code exchange wrong: " + err.Error()) c.Redirect(http.StatusTemporaryRedirect, "/") return } googleUser, err := r.userSvc.GetGoogleUser(c.Request.Context(), token.AccessToken) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) c.Redirect(http.StatusTemporaryRedirect, "/") return } @@ -179,13 +179,13 @@ func (r *HttpServer) OAuthGoogleCallback(c *gin.Context) { AuthType: GoogleAuth, }) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) c.Redirect(http.StatusTemporaryRedirect, "/") return } sid, err := r.userSvc.SetUserSession(c.Request.Context(), user.ID) if err != nil { - r.logger.Error(err) + r.logger.Error(err.Error()) response(c, http.StatusInternalServerError, common.ErrServer) return } diff --git a/pkg/web/http.go b/pkg/web/http.go index 6fc74c4..3bf9032 100644 --- a/pkg/web/http.go +++ b/pkg/web/http.go @@ -2,7 +2,9 @@ package web import ( "context" + "log/slog" "net/http" + "os" "github.com/gin-gonic/gin" "github.com/minghsu0107/go-random-chat/pkg/common" @@ -14,13 +16,13 @@ import ( type HttpServer struct { name string - logger common.HttpLogrus + logger common.HttpLog svr *gin.Engine httpPort string httpServer *http.Server } -func NewGinServer(name string, logger common.HttpLogrus) *gin.Engine { +func NewGinServer(name string, logger common.HttpLog) *gin.Engine { svr := gin.New() svr.Use(gin.Recovery()) svr.Use(common.LoggingMiddleware(logger)) @@ -34,7 +36,7 @@ func NewGinServer(name string, logger common.HttpLogrus) *gin.Engine { return svr } -func NewHttpServer(name string, logger common.HttpLogrus, config *config.Config, svr *gin.Engine) *HttpServer { +func NewHttpServer(name string, logger common.HttpLog, config *config.Config, svr *gin.Engine) *HttpServer { return &HttpServer{ name: name, logger: logger, @@ -61,10 +63,11 @@ func (r *HttpServer) Run() { Addr: addr, Handler: common.NewOtelHttpHandler(r.svr, r.name+"_http"), } - r.logger.Infoln("http server listening on ", addr) + r.logger.Info("http server listening", slog.String("addr", addr)) err := r.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { - r.logger.Fatal(err) + r.logger.Error(err.Error()) + os.Exit(1) } }() }