MSP-325 use new logger instead journal

This commit is contained in:
DeniskaRediska committed 2021-10-22 11:00:49 +03:00
1 parent 24b22aa7f1
commit 04a07377c1
4 files changed
+86 -34

No files matched your search

+11 -4
View File
@@ -2,9 +2,9 @@
package conf
import (
"github.com/integration-system/isp-journal/rx"
"github.com/integration-system/isp-lib/v2/structure"
"time"
"github.com/integration-system/isp-lib/v2/structure"
)
const (
@@ -38,8 +38,15 @@ type (
}
Journal struct {
Journal rx.Config `schema:"Настройка конфигурации"`
MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
Journal JorunalConfig `schema:"Настройка конфигурации"`
MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
}
JorunalConfig struct {
Enable bool `schema:"Включение/отключение журналирования"`
Filename string `schema:"Имя файла,путь до файла в который будут записываться логи"`
MaxSizeMb int `schema:"Максимальный размер файла,ограничение по размеру файла после достижения которого логи будут записываться в новый файл"`
Compress bool `schema:"Сжатие логов,архивирует файлы в gzip"`
}
TokensSetting struct {
+16 -12
View File
@@ -6,16 +6,15 @@ import (
"time"
"github.com/integration-system/isp-lib/v2/config"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/invoker"
"isp-gate-service/log_code"
"isp-gate-service/log"
"isp-gate-service/proxy"
"isp-gate-service/routing"
"isp-gate-service/service"
@@ -30,10 +29,13 @@ const (
var errAccounting = errors.New("accounting error")
type Handler struct {
logger log.Logger
}
func New() *Handler {
return &Handler{}
func New(logger log.Logger) *Handler {
return &Handler{
logger: logger,
}
}
func (h Handler) CompleteRequest(ctx *fasthttp.RequestCtx) {
@@ -50,17 +52,19 @@ func (h Handler) CompleteRequest(ctx *fasthttp.RequestCtx) {
}
logEnable := config.GetRemote().(*conf.RemoteConfig).JournalSetting.Journal.Enable
//nolint
// nolintlint
if logEnable && matcher.JournalMethods.Match(method) {
requestBody, responseBody, err := resp.Get()
fields := []zap.Field{
zap.Any("request", requestBody),
zap.Any("response", responseBody),
zap.String("method", method),
zap.Error(err),
}
if err != nil {
if err := invoker.Journal.Error(method, requestBody, responseBody, err); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
h.logger.Error(ctx, "unsuccessful request", fields...)
} else {
if err := invoker.Journal.Info(method, requestBody, responseBody); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
h.logger.Info(ctx, "successful request", fields...)
}
}
}
+44 -6
View File
@@ -2,19 +2,23 @@ package main
import (
"context"
"log"
"os"
"github.com/integration-system/go-cmp/cmp"
"github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/config/schema"
"github.com/integration-system/isp-lib/v2/metric"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
logrus "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/pkg/errors"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/invoker"
"isp-gate-service/log"
"isp-gate-service/proxy"
"isp-gate-service/redis"
"isp-gate-service/repository"
@@ -26,6 +30,8 @@ import (
var (
version = "0.1.0"
logger *log.Adapter
)
func main() {
@@ -43,7 +49,7 @@ func main() {
requiredModules, err := proxy.InitProxies(cfg.Locations)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
logrus.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
}
for module, consumer := range requiredModules {
bs.RequireModule(module, consumer, false)
@@ -59,10 +65,7 @@ func onLocalConfigLoad(_ *conf.Configuration) {
}
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
localCfg := config.Get().(*conf.Configuration)
repository.DbClient.ReceiveConfiguration(remoteConfig.Database)
invoker.Journal.ReceiveConfiguration(remoteConfig.JournalSetting.Journal, localCfg.ModuleName)
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns)
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
@@ -73,7 +76,16 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
metric.InitHttpServer(remoteConfig.Metrics)
service.Metrics.Init()
server.Http.Init(remoteConfig.HttpSetting, oldRemoteConfig.HttpSetting)
oldLogger := setLogger(remoteConfig.JournalSetting.Journal, oldRemoteConfig.JournalSetting.Journal)
defer func() {
if oldLogger != nil {
_ = oldLogger.Close()
}
}()
isDifferentSettingForHttpServ :=
!cmp.Equal(remoteConfig.HttpSetting, oldRemoteConfig.HttpSetting) || oldLogger != nil
server.Http.Init(isDifferentSettingForHttpServ, remoteConfig.HttpSetting.GetMaxRequestBodySize(), logger)
}
func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
@@ -94,6 +106,9 @@ func onShutdown(_ context.Context, _ os.Signal) {
proxy.Close()
_ = redis.Client.Close()
_ = invoker.Journal.Close()
if logger != nil {
_ = logger.Close()
}
}
func handleRouteUpdate(configs structure.RoutingConfig) bool {
@@ -110,3 +125,26 @@ func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
Endpoints: []structure.EndpointDescriptor{},
}
}
func setLogger(loggerCfg, oldLoggerCfg conf.JorunalConfig) *log.Adapter {
if cmp.Equal(loggerCfg, oldLoggerCfg) {
return nil
}
var err error
oldLogger := logger
if utils.DEV {
logger, err = log.New()
} else {
logger, err = log.New(log.WithFileRotation(log.Rotation{
File: loggerCfg.Filename,
MaxSizeMb: loggerCfg.MaxSizeMb,
Compress: loggerCfg.Compress,
}))
}
if err != nil {
logrus.Fatal(stdcodes.ModuleRunFatalError, errors.WithMessage(err, "set logger"))
}
return oldLogger
}
+15 -12
View File
@@ -1,15 +1,16 @@
package server
import (
"github.com/integration-system/go-cmp/cmp"
"sync"
"time"
"github.com/integration-system/isp-lib/v2/config"
log "github.com/integration-system/isp-log"
logrus "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"isp-gate-service/conf"
"isp-gate-service/handler"
"isp-gate-service/log"
"isp-gate-service/log_code"
"sync"
"time"
)
const defaultTimeout = 60 * time.Second
@@ -20,15 +21,17 @@ type httpSrv struct {
working bool
srv *fasthttp.Server
mx sync.Mutex
logger log.Logger
}
func (s *httpSrv) Init(new, old conf.HttpSetting) {
func (s *httpSrv) Init(isDifferentSetting bool, bodySize int64, logger log.Logger) {
s.logger = logger
if s.working {
if !cmp.Equal(new, old) {
s.run(new.GetMaxRequestBodySize())
if isDifferentSetting {
s.run(bodySize)
}
} else {
s.run(new.GetMaxRequestBodySize())
s.run(bodySize)
}
}
@@ -37,20 +40,20 @@ func (s *httpSrv) run(maxRequestBodySize int64) {
s.working = true
if s.srv != nil {
if err := s.srv.Shutdown(); err != nil {
log.Warn(log_code.WarnHttpServerShutdown, err)
logrus.Warn(log_code.WarnHttpServerShutdown, err)
}
}
localConfig := config.Get().(*conf.Configuration)
restAddress := localConfig.HttpInnerAddress.GetAddress()
s.srv = &fasthttp.Server{
Handler: handler.New().CompleteRequest,
Handler: handler.New(s.logger).CompleteRequest,
WriteTimeout: defaultTimeout,
ReadTimeout: defaultTimeout,
MaxRequestBodySize: int(maxRequestBodySize),
}
go func() {
if err := s.srv.ListenAndServe(restAddress); err != nil {
log.Error(log_code.ErrorHttpServerListen, err)
logrus.Error(log_code.ErrorHttpServerListen, err)
}
}()
s.mx.Unlock()
@@ -60,7 +63,7 @@ func (s *httpSrv) Close() {
if s.srv != nil {
s.working = false
if err := s.srv.Shutdown(); err != nil {
log.Warn(log_code.WarnHttpServerShutdown, err)
logrus.Warn(log_code.WarnHttpServerShutdown, err)
}
}
}