Skip to content

Commit

Permalink
Merge pull request #7 from solumD/Task-7
Browse files Browse the repository at this point in the history
Task 7
  • Loading branch information
solumD authored Nov 28, 2024
2 parents 6e6987f + 7a7d5f7 commit cd10361
Show file tree
Hide file tree
Showing 23 changed files with 232 additions and 18 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ MIGRATION_DSN="host=pg port=5432 dbname=chat user=chat-user password=chat-passwo
GRPC_HOST=localhost
GRPC_PORT=50052

LOGGER_LEVEL=info

HTTP_HOST=localhost
HTTP_PORT=8081

Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
/bin
/coverage.out
/tls/
/vendor.protogen
/vendor.protogen
/logs/
7 changes: 6 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20241021214115-324edc3d5d38
)

require gopkg.in/yaml.v3 v3.0.1 // indirect
require (
go.uber.org/multierr v1.10.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

require (
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
Expand All @@ -42,8 +45,10 @@ require (
require (
github.com/brianvoe/gofakeit/v7 v7.1.2
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/natefinch/lumberjack v2.0.0+incompatible
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rs/cors v1.11.1
go.uber.org/zap v1.27.0
golang.org/x/net v0.28.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.19.0 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand Down Expand Up @@ -213,11 +215,15 @@ go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
Expand Down
6 changes: 4 additions & 2 deletions internal/api/chat/create_chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package chat

import (
"context"
"log"

"github.com/solumD/chat-server/internal/api/chat/errors"
"github.com/solumD/chat-server/internal/converter"
"github.com/solumD/chat-server/internal/logger"
desc "github.com/solumD/chat-server/pkg/chat_v1"

"go.uber.org/zap"
)

// CreateChat отправляет запрос в сервисный слой на создание чата
Expand All @@ -21,7 +23,7 @@ func (i *API) CreateChat(ctx context.Context, req *desc.CreateChatRequest) (*des
return nil, err
}

log.Printf("inserted chat with id %d", chatID)
logger.Info("inserted chat", zap.Int64("chatID", chatID))

return &desc.CreateChatResponse{
Id: chatID,
Expand Down
4 changes: 3 additions & 1 deletion internal/api/chat/delete_chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
"fmt"
"log"

"github.com/solumD/chat-server/internal/logger"
desc "github.com/solumD/chat-server/pkg/chat_v1"

"go.uber.org/zap"
"google.golang.org/protobuf/types/known/emptypb"
)

Expand All @@ -21,7 +23,7 @@ func (i *API) DeleteChat(ctx context.Context, req *desc.DeleteChatRequest) (*emp
return nil, err
}

log.Printf("deleted chat with id %d", req.GetId())
logger.Info("deleted chat", zap.Int64("chatID", req.GetId()))

return &emptypb.Empty{}, nil
}
5 changes: 3 additions & 2 deletions internal/api/chat/send_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package chat

import (
"context"
"log"

"github.com/solumD/chat-server/internal/api/chat/errors"
"github.com/solumD/chat-server/internal/converter"
"github.com/solumD/chat-server/internal/logger"
desc "github.com/solumD/chat-server/pkg/chat_v1"

"go.uber.org/zap"
"google.golang.org/protobuf/types/known/emptypb"
)

Expand All @@ -22,7 +23,7 @@ func (i *API) SendMessage(ctx context.Context, req *desc.SendMessageRequest) (*e
return nil, err
}

log.Printf("sent message in chat %d", req.GetId())
logger.Info("sent message in chat", zap.Int64("chatID", req.GetId()))

return &emptypb.Empty{}, nil
}
3 changes: 3 additions & 0 deletions internal/api/chat/tests/create_chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/solumD/chat-server/internal/api/chat"
"github.com/solumD/chat-server/internal/api/chat/errors"
"github.com/solumD/chat-server/internal/logger"
"github.com/solumD/chat-server/internal/model"
"github.com/solumD/chat-server/internal/service"
serviceMocks "github.com/solumD/chat-server/internal/service/mocks"
Expand Down Expand Up @@ -103,6 +104,8 @@ func TestCreateChat(t *testing.T) {
},
}

logger.MockInit()

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
Expand Down
3 changes: 3 additions & 0 deletions internal/api/chat/tests/delete_chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/solumD/chat-server/internal/api/chat"
"github.com/solumD/chat-server/internal/logger"
"github.com/solumD/chat-server/internal/service"
serviceMocks "github.com/solumD/chat-server/internal/service/mocks"
desc "github.com/solumD/chat-server/pkg/chat_v1"
Expand Down Expand Up @@ -93,6 +94,8 @@ func TestDeleteChat(t *testing.T) {
},
}

logger.MockInit()

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
Expand Down
3 changes: 3 additions & 0 deletions internal/api/chat/tests/send_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/solumD/chat-server/internal/api/chat"
"github.com/solumD/chat-server/internal/api/chat/errors"
"github.com/solumD/chat-server/internal/logger"
"github.com/solumD/chat-server/internal/model"
"github.com/solumD/chat-server/internal/service"
serviceMocks "github.com/solumD/chat-server/internal/service/mocks"
Expand Down Expand Up @@ -104,6 +105,8 @@ func TestSendMessage(t *testing.T) {
},
}

logger.MockInit()

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/solumD/chat-server/internal/closer"
"github.com/solumD/chat-server/internal/config"
"github.com/solumD/chat-server/internal/interceptor"
"github.com/solumD/chat-server/internal/logger"
desc "github.com/solumD/chat-server/pkg/chat_v1"
_ "github.com/solumD/chat-server/statik" //

Expand Down Expand Up @@ -136,9 +137,12 @@ func (a *App) initGRPCServer(ctx context.Context) {
log.Fatalf("failed to load TLS keys: %v", err)
}

logger.Init(logger.GetCore(logger.GetAtomicLevel(a.serviceProvider.LoggerConfig().Level())))

a.grpcServer = grpc.NewServer(
grpc.UnaryInterceptor(
grpcMW.ChainUnaryServer(
interceptor.LogInterceptor,
interceptor.ValidateInterceptor,
interceptor.NewAuthInterceptor(a.serviceProvider.AuthClient(ctx)).Get()),
),
Expand Down
16 changes: 16 additions & 0 deletions internal/app/service_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
chatRepo "github.com/solumD/chat-server/internal/repository/chat"
"github.com/solumD/chat-server/internal/service"
chatSrv "github.com/solumD/chat-server/internal/service/chat"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
Expand All @@ -27,6 +28,7 @@ type serviceProvider struct {
httpConfig config.HTTPConfig
swaggerConfig config.SwaggerConfig
authConfig config.AuthConfig
loggerConfig config.LoggerConfig

dbClient db.Client
txManager db.TxManager
Expand Down Expand Up @@ -70,6 +72,20 @@ func (s *serviceProvider) GRPCConfig() config.GRPCConfig {
return s.grpcConfig
}

// LoggerConfig инициализирует конфиг логгера
func (s *serviceProvider) LoggerConfig() config.LoggerConfig {
if s.loggerConfig == nil {
cfg, err := config.NewLoggerConfig()
if err != nil {
log.Fatalf("failed to get logger config:%v", err)
}

s.loggerConfig = cfg
}

return s.loggerConfig
}

// HTTPConfig ининициализирует конфиг http сервера
func (s *serviceProvider) HTTPConfig() config.HTTPConfig {
if s.httpConfig == nil {
Expand Down
11 changes: 4 additions & 7 deletions internal/client/db/pg/pg.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package pg

import (
"context"
"fmt"
"log"

"github.com/solumD/chat-server/internal/client/db"
"github.com/solumD/chat-server/internal/client/db/prettier"
"github.com/solumD/chat-server/internal/logger"
"go.uber.org/zap"

"github.com/georgysavva/scany/pgxscan"
"github.com/jackc/pgconn"
Expand Down Expand Up @@ -114,9 +114,6 @@ func MakeContextTx(ctx context.Context, tx pgx.Tx) context.Context {

func logQuery(ctx context.Context, q db.Query, args ...interface{}) {
prettyQuery := prettier.Pretty(q.QueryRaw, prettier.PlaceholderDollar, args...)
log.Println(
ctx,
fmt.Sprintf("sql: %s", q.Name),
fmt.Sprintf("query: %s", prettyQuery),
)
logger.Debug(
"", zap.Any("ctx", ctx), zap.String("sql", q.Name), zap.String("query", prettyQuery))
}
5 changes: 5 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ type GRPCConfig interface {
Address() string
}

// LoggerConfig интерфейс конфига логгера
type LoggerConfig interface {
Level() string
}

// PGConfig is interface of a postgres config
type PGConfig interface {
DSN() string
Expand Down
31 changes: 31 additions & 0 deletions internal/config/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package config

import (
"errors"
"os"
)

const (
loggerLevelEnvName = "LOGGER_LEVEL"
)

type loggerConfig struct {
level string
}

// NewLoggerConfig returns new grpc config
func NewLoggerConfig() (LoggerConfig, error) {
level := os.Getenv(loggerLevelEnvName)
if len(level) == 0 {
return nil, errors.New("logger level not found")
}

return &loggerConfig{
level: level,
}, nil
}

// Level returns level of logger
func (cfg *loggerConfig) Level() string {
return cfg.level
}
25 changes: 25 additions & 0 deletions internal/interceptor/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package interceptor

import (
"context"
"time"

"github.com/solumD/chat-server/internal/logger"

"go.uber.org/zap"
"google.golang.org/grpc"
)

// LogInterceptor логирует содержание запроса
func LogInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
now := time.Now()

res, err := handler(ctx, req)
if err != nil {
logger.Error(err.Error(), zap.String("method", info.FullMethod), zap.Any("req", req))
}

logger.Info("request", zap.String("method", info.FullMethod), zap.Any("req", req), zap.Any("res", res), zap.Duration("duration", time.Since(now)))

return res, err
}
59 changes: 59 additions & 0 deletions internal/logger/funcs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package logger

import (
"log"
"os"

"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

const (
logsFilePath = "logs/app.log"
fileMegabytesMaxSize = 10
fileMaxBackupsCount = 3
fileMaxAge = 7 // days
)

// GetCore возвращает настройки логгера
func GetCore(level zap.AtomicLevel) zapcore.Core {
stdout := zapcore.AddSync(os.Stdout)

file := zapcore.AddSync(&lumberjack.Logger{
Filename: logsFilePath,
MaxSize: fileMegabytesMaxSize,
MaxBackups: fileMaxBackupsCount,
MaxAge: fileMaxAge,
})

productionCfg := zap.NewProductionEncoderConfig()
productionCfg.TimeKey = "timestamp"
productionCfg.EncodeTime = zapcore.ISO8601TimeEncoder

developmentCfg := zap.NewDevelopmentEncoderConfig()
developmentCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder

consoleEncoder := zapcore.NewConsoleEncoder(developmentCfg)
fileEncoder := zapcore.NewJSONEncoder(productionCfg)

return zapcore.NewTee(
zapcore.NewCore(consoleEncoder, stdout, level),
zapcore.NewCore(fileEncoder, file, level),
)
}

// GetAtomicLevel возвращает уровень логгирования
func GetAtomicLevel(logLevel string) zap.AtomicLevel {
var level zapcore.Level
if err := level.Set(logLevel); err != nil {
log.Fatalf("failed to set log level: %v", err)
}

return zap.NewAtomicLevelAt(level)
}

// MockInit инициализирует логгер для моков
func MockInit() {
globalLogger = zap.NewNop()
}
Loading

0 comments on commit cd10361

Please sign in to comment.