Skip to content
Snippets Groups Projects
Commit a0d26b94 authored by ko_oler's avatar ko_oler
Browse files

Merge remote-tracking branch 'origin/feature/PRXS-951-Log' into feature/PRXS-951-Log

parents 6c29d1c8 18858016
No related branches found
No related tags found
No related merge requests found
Showing
with 1005 additions and 1220 deletions
......@@ -6,8 +6,9 @@ import (
"go.uber.org/zap"
)
{{ $funcName := (or .Vars.FuncName ("LoggingMiddleware")) }}
{{ $decorator := (or .Vars.DecoratorName ("loggingMiddleware")) }}
{{ $funcName := (or .Vars.FuncName ("AccessLoggingMiddleware")) }}
{{ $decorator := (or .Vars.DecoratorName ("accessLoggingMiddleware")) }}
{{ $objectName := (trimSuffix "s" (split "." .Interface.Type)._1) }}
// {{$decorator}} implements {{.Interface.Type}} that is instrumented with logging
type {{$decorator}} struct {
......@@ -28,37 +29,29 @@ func {{$funcName}}(logger *zap.Logger) Middleware {
{{range $method := .Interface.Methods}}
func (m *{{$decorator}}) {{$method.Declaration}} {
begin := time.Now()
var fields []zapcore.Field
{{- if $method.HasParams}}
for k, v := range {{$method.ParamsMap}} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k,v))
}
{{end}}
m.logger.Debug("{{$method.Name}}.Request",fields...)
m.logger.Debug("{{$method.Name}}.Request",
{{- range $param := $method.Params -}}
{{- if (eq $param.Name "ctx") }}
zap.Reflect("principal", auth.GetPrincipal(ctx)),
{{- else }}
zap.Reflect("{{$param.Name}}", {{$param.Name}}),
{{- end -}}
{{ end }}
)
{{ $method.ResultsNames }} = m.next.{{ $method.Call }}
fields = []zapcore.Field{
m.logger.Debug("{{$method.Name}}.Response",
zap.Duration("time", time.Since(begin)),
}
{{ if $method.HasResults}}
for k, v := range {{$method.ResultsMap}} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
}
fields = append(fields, zap.Reflect(k,v))
}
{{- range $param := $method.Results -}}
{{- if (eq $param.Name "err") }}
zap.Error(err),
{{- else }}
zap.Reflect("{{$param.Name}}", {{$param.Name}}),
{{- end -}}
{{ end }}
m.logger.Debug("{{$method.Name}}.Response", fields...)
)
return {{ $method.ResultsNames }}
}
......
{{/*
Этот шаблон предназначен только для первичной генерации LoggingMiddleware,
поскольку он не может учесть все сигнатуры логгируемых методов. После генерации
необходимо внести правки в код в местах, помеченных 'TODO'
Сгенерировать middleware:
```shell
gowrap gen -p git.perx.ru/perxis/perxis-go/<package_name> -i <interface> -t ../../../assets/templates/middleware/logging.tmpl -o info_logging_middleware.go -g
```
*/}}
import (
"fmt"
"time"
"context"
logzap "git.perx.ru/perxis/perxis-go/zap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
{{ $funcName := (or .Vars.FuncName ("LoggingMiddleware")) }}
{{ $decorator := (or .Vars.DecoratorName ("loggingMiddleware")) }}
{{ $packageName := (split "." .Interface.Type)._0 }}
{{ $serviceName := (split "." .Interface.Type)._1 }}
{{ $objectName := (trimSuffix "s" (split "." .Interface.Type)._1) }}
{{ $writeMethods := list "Archive" "Create" "Delete" "Publish" "Unarchive" "Undelete" "Unpublish" "Update" "SetSchema" "Migrate" }}
type {{ $decorator }} struct {
logger *zap.Logger
next {{ .Interface.Type }}
}
func {{ $funcName }} (logger *zap.Logger) Middleware {
return func(next {{ .Interface.Type }}) {{ .Interface.Type }} {
return &{{ $decorator }}{
next: next,
logger: logger.With(logzap.Component("{{ (lower $serviceName ) }}")),
}
}
}
{{ range $method := .Interface.Methods }}
func (m *{{ $decorator }}) {{ $method.Declaration }} {
logger := m.logger.With(
{{- if $method.AcceptsContext }}
logzap.CallerFromContext(ctx),
{{ end -}}
{{- if has $method.Name $writeMethods -}}
logzap.Event({{ $packageName }}.Event{{ $objectName }}{{ $method.Name }}),
logzap.Object(TODO),
{{ end -}}
)
{{ $method.ResultsNames }} = m.next.{{ $method.Call }}
{{- if $method.ReturnsError }}
if err != nil {
logger.Error("Failed to {{ (lower $method.Name) }}", zap.Error(err)
{{- if has $method.Name $writeMethods -}}
, logzap.Channels(logzap.Userlog, logzap.Syslog)
{{- end -}})
return
}
{{ end }}
{{ if has $method.Name $writeMethods }}
logger.Info("Successfully {{ (lower (trimSuffix "e" $method.Name)) }}ed", logzap.Channels(logzap.Userlog))
{{ end -}}
return {{ $method.ResultsNames }}
}
{{ end }}
......@@ -2,20 +2,26 @@ import (
"go.uber.org/zap"
)
type Middleware func({{.Interface.Type}}) {{.Interface.Type}}
{{ $serviceName := (split "." .Interface.Type)._1 }}
type Middleware func({{.Interface.Type}}) {{.Interface.Type}}
func WithLog(s {{.Interface.Type}}, logger *zap.Logger, log_access bool) {{.Interface.Type}} {
if logger == nil {
logger = zap.NewNop()
}
logger = logger.Named("{{ .Interface.Name }}")
{{- if (has $serviceName (list "Items" "Collections") ) }}
if log_access {
s = AccessLoggingMiddleware(logger)(s)
}
s = LoggingMiddleware(logger)(s)
{{ else }}
s = ErrorLoggingMiddleware(logger)(s)
if log_access {
s = LoggingMiddleware(logger)(s)
}
{{ end -}}
s = RecoveringMiddleware(logger)(s)
return s
}
......@@ -8,6 +8,8 @@ import (
pb "git.perx.ru/perxis/perxis-go/proto/log"
)
const ServiceName = "logs"
type Service interface {
// Log метод записи логов
......
......@@ -53,16 +53,12 @@ func TestBufferedWriteSyncer_Write_Concurrent(t *testing.T) {
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
err := ws.Write(&log.Entry{Message: "log message"})
require.NoError(t, err)
require.NoError(t, ws.Write(&log.Entry{Message: "log message"}))
}(&wg)
}
wg.Wait()
err := ws.Stop()
require.NoError(t, err)
require.NoError(t, ws.Stop())
service.AssertExpectations(t)
}
......@@ -81,15 +77,12 @@ func TestBufferedWriteSyncer_Flush(t *testing.T) {
for i := 0; i < 10; i++ {
for j := 0; j < 10; j++ {
err := ws.Write(&log.Entry{Message: "log message"})
require.NoError(t, err)
require.NoError(t, ws.Write(&log.Entry{Message: "log message"}))
}
err := ws.Sync()
require.NoError(t, err)
require.NoError(t, ws.Sync())
}
err := ws.Stop()
require.NoError(t, err)
require.NoError(t, ws.Stop())
service.AssertExpectations(t)
}
......@@ -107,12 +100,10 @@ func TestBufferedWriteSyncer_MaxBufferSize(t *testing.T) {
ws := &BufferedWriteSyncer{Service: service, MaxBufferSize: 10}
for i := 0; i < 100; i++ {
err := ws.Write(&log.Entry{Message: "log message"})
require.NoError(t, err)
require.NoError(t, ws.Write(&log.Entry{Message: "log message"}))
}
err := ws.Stop()
require.NoError(t, err)
require.NoError(t, ws.Stop())
service.AssertExpectations(t)
}
......@@ -130,14 +121,11 @@ func TestBufferedWriteSyncer_FlushInterval(t *testing.T) {
ws := &BufferedWriteSyncer{Service: service, FlushInterval: time.Second}
for j := 0; j < 10; j++ {
err := ws.Write(&log.Entry{Message: "log message"})
require.NoError(t, err)
require.NoError(t, ws.Write(&log.Entry{Message: "log message"}))
}
time.Sleep(3 * time.Second) // ждем, пока сработает интервал
err := ws.Stop()
require.NoError(t, err)
require.NoError(t, ws.Stop())
service.AssertExpectations(t)
}
package zap
import (
"fmt"
oid "git.perx.ru/perxis/perxis-go/id"
"git.perx.ru/perxis/perxis-go/log"
"git.perx.ru/perxis/perxis-go/pkg/id"
......@@ -76,6 +78,10 @@ func (core *Core) getEntry(entry zapcore.Entry, fields []zapcore.Field) *log.Ent
ent.CallerID, _ = enc.Fields["caller"].(*oid.ObjectId)
ent.Attr = enc.Fields["attr"]
if err, _ := enc.Fields["error"].(error); err != nil {
ent.Message = fmt.Sprintf("%s. Error: %s", ent.Message, err.Error())
}
if tags, ok := enc.Fields["tags"].([]any); ok {
for _, item := range tags {
if tag, ok := item.(string); ok {
......
......@@ -5,7 +5,7 @@ import (
"git.perx.ru/perxis/perxis-go/id"
"git.perx.ru/perxis/perxis-go/log"
zap2 "git.perx.ru/perxis/perxis-go/zap"
logzap "git.perx.ru/perxis/perxis-go/zap"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
......@@ -31,13 +31,13 @@ func TestCore_getEntry(t *testing.T) {
entry: zapcore.Entry{Level: zapcore.InfoLevel, Message: "создан элемент коллекции"},
fields: []zapcore.Field{
zap.String("key", "val"), // будет проигнорировано
zap2.Category("create"),
zap2.Component("Items.Service"),
zap2.Event("Items.Create"),
zap2.Object("/spaces/WPNN/envs/9VGP/cols/GxNv/items/W0fl"),
zap2.Caller("/users/PHVz"),
zap2.Attr("any"),
zap2.Tags("tag1", "tag2", "tag3"),
logzap.Category("create"),
logzap.Component("Items.Service"),
logzap.Event("Items.Create"),
logzap.Object("/spaces/WPNN/envs/9VGP/cols/GxNv/items/W0fl"),
logzap.Caller("/users/PHVz"),
logzap.Attr("any"),
logzap.Tags("tag1", "tag2", "tag3"),
},
},
want: &log.Entry{
......
......@@ -13,7 +13,7 @@ import (
"git.perx.ru/perxis/perxis-go/pkg/items"
"git.perx.ru/perxis/perxis-go/pkg/users"
usersmocks "git.perx.ru/perxis/perxis-go/pkg/users/mocks"
zap2 "git.perx.ru/perxis/perxis-go/zap"
logzap "git.perx.ru/perxis/perxis-go/zap"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
......@@ -29,7 +29,7 @@ func TestExample(t *testing.T) {
LogLevel: log.Level(zapcore.InfoLevel),
Message: "Successfully created",
Component: "Items",
Event: items.EventCreateItem,
Event: items.EventItemCreate,
ObjectID: id.MustObjectId(item),
CallerID: id.MustObjectId(user),
Tags: []string{"tag1", "tag2", "tag3"},
......@@ -38,7 +38,7 @@ func TestExample(t *testing.T) {
LogLevel: log.Level(zapcore.WarnLevel),
Message: "Successfully updated",
Component: "Items",
Event: items.EventUpdateItem,
Event: items.EventItemUpdate,
ObjectID: id.MustObjectId(item),
CallerID: id.MustObjectId(user),
Attr: map[string]map[string]any{"title": {"old": "old title", "new": "new title"}},
......@@ -70,23 +70,23 @@ func TestExample(t *testing.T) {
// Пример отправки логов для сервиса Items
{
logger := logger.With(zap2.Component("Items"))
logger := logger.With(logzap.Component("Items"))
ctx := auth.WithPrincipal(context.Background(), factory.User("74d90aaf"))
// Отправка лога при создании item
logger.Info("Successfully created",
zap2.Event(items.EventCreateItem),
zap2.Object(item),
zap2.CallerFromContext(ctx),
zap2.Tags("tag1", "tag2", "tag3"),
logzap.Event(items.EventItemCreate),
logzap.Object(item),
logzap.CallerFromContext(ctx),
logzap.Tags("tag1", "tag2", "tag3"),
)
// Отправка лога при обновлении item
logger.Warn("Successfully updated",
zap2.Event(items.EventUpdateItem),
zap2.Object(item),
zap2.CallerFromContext(ctx),
zap2.Attr(map[string]map[string]any{"title": {"old": "old title", "new": "new title"}}),
logzap.Event(items.EventItemUpdate),
logzap.Object(item),
logzap.CallerFromContext(ctx),
logzap.Attr(map[string]map[string]any{"title": {"old": "old title", "new": "new title"}}),
)
}
......
package collections
const (
EventCollectionCreate = "collection_create"
EventCollectionUpdate = "collection_update"
EventCollectionDelete = "collection_delete"
EventCollectionSetSchema = "collection_set_schema"
)
// Code generated by gowrap. DO NOT EDIT.
// template: ../../../assets/templates/middleware/access_log.tmpl
// gowrap: http://github.com/hexdigest/gowrap
package middleware
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/collections -i Collections -t ../../../assets/templates/middleware/access_log.tmpl -o access_logging_middleware.go -l ""
import (
"context"
"time"
"git.perx.ru/perxis/perxis-go/pkg/auth"
"git.perx.ru/perxis/perxis-go/pkg/collections"
"git.perx.ru/perxis/perxis-go/pkg/schema"
"go.uber.org/zap"
)
// accessLoggingMiddleware implements collections.Collections that is instrumented with logging
type accessLoggingMiddleware struct {
logger *zap.Logger
next collections.Collections
}
// AccessLoggingMiddleware instruments an implementation of the collections.Collections with simple logging
func AccessLoggingMiddleware(logger *zap.Logger) Middleware {
return func(next collections.Collections) collections.Collections {
return &accessLoggingMiddleware{
next: next,
logger: logger,
}
}
}
func (m *accessLoggingMiddleware) Create(ctx context.Context, collection *collections.Collection) (created *collections.Collection, err error) {
begin := time.Now()
m.logger.Debug("Create.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("collection", collection),
)
created, err = m.next.Create(ctx, collection)
m.logger.Debug("Create.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("created", created),
zap.Error(err),
)
return created, err
}
func (m *accessLoggingMiddleware) Delete(ctx context.Context, spaceId string, envId string, collectionId string) (err error) {
begin := time.Now()
m.logger.Debug("Delete.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
)
err = m.next.Delete(ctx, spaceId, envId, collectionId)
m.logger.Debug("Delete.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Get(ctx context.Context, spaceId string, envId string, collectionId string, options ...*collections.GetOptions) (collection *collections.Collection, err error) {
begin := time.Now()
m.logger.Debug("Get.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("options", options),
)
collection, err = m.next.Get(ctx, spaceId, envId, collectionId, options...)
m.logger.Debug("Get.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("collection", collection),
zap.Error(err),
)
return collection, err
}
func (m *accessLoggingMiddleware) List(ctx context.Context, spaceId string, envId string, filter *collections.Filter) (collections []*collections.Collection, err error) {
begin := time.Now()
m.logger.Debug("List.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("filter", filter),
)
collections, err = m.next.List(ctx, spaceId, envId, filter)
m.logger.Debug("List.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("collections", collections),
zap.Error(err),
)
return collections, err
}
func (m *accessLoggingMiddleware) SetSchema(ctx context.Context, spaceId string, envId string, collectionId string, schema *schema.Schema) (err error) {
begin := time.Now()
m.logger.Debug("SetSchema.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("schema", schema),
)
err = m.next.SetSchema(ctx, spaceId, envId, collectionId, schema)
m.logger.Debug("SetSchema.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) SetState(ctx context.Context, spaceId string, envId string, collectionId string, state *collections.StateInfo) (err error) {
begin := time.Now()
m.logger.Debug("SetState.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("state", state),
)
err = m.next.SetState(ctx, spaceId, envId, collectionId, state)
m.logger.Debug("SetState.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Update(ctx context.Context, coll *collections.Collection) (err error) {
begin := time.Now()
m.logger.Debug("Update.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("coll", coll),
)
err = m.next.Update(ctx, coll)
m.logger.Debug("Update.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
package middleware
// Code generated by gowrap. DO NOT EDIT.
// template: ../../../assets/templates/middleware/error_log
// gowrap: http://github.com/hexdigest/gowrap
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/collections -i Collections -t ../../../assets/templates/middleware/error_log -o error_logging_middleware.go -l ""
import (
"context"
"git.perx.ru/perxis/perxis-go/pkg/collections"
"git.perx.ru/perxis/perxis-go/pkg/schema"
"go.uber.org/zap"
)
// errorLoggingMiddleware implements collections.Collections that is instrumented with logging
type errorLoggingMiddleware struct {
logger *zap.Logger
next collections.Collections
}
// ErrorLoggingMiddleware instruments an implementation of the collections.Collections with simple logging
func ErrorLoggingMiddleware(logger *zap.Logger) Middleware {
return func(next collections.Collections) collections.Collections {
return &errorLoggingMiddleware{
next: next,
logger: logger,
}
}
}
func (m *errorLoggingMiddleware) Create(ctx context.Context, collection *collections.Collection) (created *collections.Collection, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Create(ctx, collection)
}
func (m *errorLoggingMiddleware) Delete(ctx context.Context, spaceId string, envId string, collectionId string) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Delete(ctx, spaceId, envId, collectionId)
}
func (m *errorLoggingMiddleware) Get(ctx context.Context, spaceId string, envId string, collectionId string, options ...*collections.GetOptions) (collection *collections.Collection, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Get(ctx, spaceId, envId, collectionId, options...)
}
func (m *errorLoggingMiddleware) List(ctx context.Context, spaceId string, envId string, filter *collections.Filter) (collections []*collections.Collection, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.List(ctx, spaceId, envId, filter)
}
func (m *errorLoggingMiddleware) SetSchema(ctx context.Context, spaceId string, envId string, collectionId string, schema *schema.Schema) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.SetSchema(ctx, spaceId, envId, collectionId, schema)
}
func (m *errorLoggingMiddleware) SetState(ctx context.Context, spaceId string, envId string, collectionId string, state *collections.StateInfo) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.SetState(ctx, spaceId, envId, collectionId, state)
}
func (m *errorLoggingMiddleware) Update(ctx context.Context, coll *collections.Collection) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Update(ctx, coll)
}
package middleware
// Code generated by gowrap. DO NOT EDIT.
// template: ../../../assets/templates/middleware/access_log
// template: ../../../assets/templates/middleware/log.tmpl
// gowrap: http://github.com/hexdigest/gowrap
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/collections -i Collections -t ../../../assets/templates/middleware/access_log -o logging_middleware.go -l ""
package middleware
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/collections -i Collections -t ../../../assets/templates/middleware/log.tmpl -o logging_middleware.go -l ""
import (
"context"
"fmt"
"time"
"git.perx.ru/perxis/perxis-go/pkg/auth"
"git.perx.ru/perxis/perxis-go/id"
"git.perx.ru/perxis/perxis-go/pkg/collections"
"git.perx.ru/perxis/perxis-go/pkg/schema"
logzap "git.perx.ru/perxis/perxis-go/zap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// loggingMiddleware implements collections.Collections that is instrumented with logging
type loggingMiddleware struct {
logger *zap.Logger
next collections.Collections
}
// LoggingMiddleware instruments an implementation of the collections.Collections with simple logging
func LoggingMiddleware(logger *zap.Logger) Middleware {
return func(next collections.Collections) collections.Collections {
return &loggingMiddleware{
next: next,
logger: logger,
logger: logger.With(logzap.Component("collections")),
}
}
}
func (m *loggingMiddleware) Create(ctx context.Context, collection *collections.Collection) (created *collections.Collection, err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"collection": collection} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Create.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
logzap.Event(collections.EventCollectionCreate),
)
created, err = m.next.Create(ctx, collection)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
if err != nil {
logger.Error("Failed to create", zap.Error(err), logzap.Object(collection), logzap.Channels(logzap.Userlog, logzap.Syslog))
return
}
for k, v := range map[string]interface{}{
"created": created,
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Create.Response", fields...)
logger.Info("Successfully created", logzap.Object(created), logzap.Channels(logzap.Userlog))
return created, err
}
func (m *loggingMiddleware) Delete(ctx context.Context, spaceId string, envId string, collectionId string) (err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"spaceId": spaceId,
"envId": envId,
"collectionId": collectionId} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Delete.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
logzap.Event(collections.EventCollectionDelete),
logzap.Object(id.NewCollectionId(spaceId, envId, collectionId)),
)
err = m.next.Delete(ctx, spaceId, envId, collectionId)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
}
for k, v := range map[string]interface{}{
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
if err != nil {
logger.Error("Failed to delete", zap.Error(err), logzap.Channels(logzap.Userlog, logzap.Syslog))
return
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Delete.Response", fields...)
logger.Info("Successfully deleted", logzap.Channels(logzap.Userlog))
return err
}
func (m *loggingMiddleware) Get(ctx context.Context, spaceId string, envId string, collectionId string, options ...*collections.GetOptions) (collection *collections.Collection, err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"spaceId": spaceId,
"envId": envId,
"collectionId": collectionId,
"options": options} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Get.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
)
collection, err = m.next.Get(ctx, spaceId, envId, collectionId, options...)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
}
for k, v := range map[string]interface{}{
"collection": collection,
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
}
fields = append(fields, zap.Reflect(k, v))
if err != nil {
logger.Error("Failed to get", zap.Error(err))
return
}
m.logger.Debug("Get.Response", fields...)
return collection, err
}
func (m *loggingMiddleware) List(ctx context.Context, spaceId string, envId string, filter *collections.Filter) (collections []*collections.Collection, err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"spaceId": spaceId,
"envId": envId,
"filter": filter} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("List.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
)
collections, err = m.next.List(ctx, spaceId, envId, filter)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
}
for k, v := range map[string]interface{}{
"collections": collections,
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
}
fields = append(fields, zap.Reflect(k, v))
if err != nil {
logger.Error("Failed to list", zap.Error(err))
return
}
m.logger.Debug("List.Response", fields...)
return collections, err
}
func (m *loggingMiddleware) SetSchema(ctx context.Context, spaceId string, envId string, collectionId string, schema *schema.Schema) (err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"spaceId": spaceId,
"envId": envId,
"collectionId": collectionId,
"schema": schema} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("SetSchema.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
logzap.Event(collections.EventCollectionSetSchema),
logzap.Object(id.NewCollectionId(spaceId, envId, collectionId)),
)
err = m.next.SetSchema(ctx, spaceId, envId, collectionId, schema)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
}
for k, v := range map[string]interface{}{
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
if err != nil {
logger.Error("Failed to setschema", zap.Error(err), logzap.Channels(logzap.Userlog, logzap.Syslog))
return
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("SetSchema.Response", fields...)
logger.Info("Successfully setschemaed", logzap.Channels(logzap.Userlog))
return err
}
func (m *loggingMiddleware) SetState(ctx context.Context, spaceId string, envId string, collectionId string, state *collections.StateInfo) (err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"spaceId": spaceId,
"envId": envId,
"collectionId": collectionId,
"state": state} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("SetState.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
)
err = m.next.SetState(ctx, spaceId, envId, collectionId, state)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
}
for k, v := range map[string]interface{}{
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
}
fields = append(fields, zap.Reflect(k, v))
if err != nil {
logger.Error("Failed to setstate", zap.Error(err))
return
}
m.logger.Debug("SetState.Response", fields...)
return err
}
func (m *loggingMiddleware) Update(ctx context.Context, coll *collections.Collection) (err error) {
begin := time.Now()
var fields []zapcore.Field
for k, v := range map[string]interface{}{
"ctx": ctx,
"coll": coll} {
if k == "ctx" {
fields = append(fields, zap.String("principal", fmt.Sprint(auth.GetPrincipal(ctx))))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Update.Request", fields...)
logger := m.logger.With(
logzap.CallerFromContext(ctx),
logzap.Event(collections.EventCollectionUpdate),
logzap.Object(coll),
)
err = m.next.Update(ctx, coll)
fields = []zapcore.Field{
zap.Duration("time", time.Since(begin)),
if err != nil {
logger.Error("Failed to update", zap.Error(err), logzap.Channels(logzap.Userlog, logzap.Syslog))
return
}
for k, v := range map[string]interface{}{
"err": err} {
if k == "err" {
err, _ := v.(error)
fields = append(fields, zap.Error(err))
continue
}
fields = append(fields, zap.Reflect(k, v))
}
m.logger.Debug("Update.Response", fields...)
logger.Info("Successfully updated", logzap.Channels(logzap.Userlog))
return err
}
// Code generated by gowrap. DO NOT EDIT.
// template: ../../../assets/templates/middleware/middleware
// template: ../../../assets/templates/middleware/middleware.tmpl
// gowrap: http://github.com/hexdigest/gowrap
package middleware
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/collections -i Collections -t ../../../assets/templates/middleware/middleware -o middleware.go -l ""
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/collections -i Collections -t ../../../assets/templates/middleware/middleware.tmpl -o middleware.go -l ""
import (
"git.perx.ru/perxis/perxis-go/pkg/collections"
......@@ -17,12 +17,11 @@ func WithLog(s collections.Collections, logger *zap.Logger, log_access bool) col
if logger == nil {
logger = zap.NewNop()
}
logger = logger.Named("Collections")
s = ErrorLoggingMiddleware(logger)(s)
if log_access {
s = LoggingMiddleware(logger)(s)
s = AccessLoggingMiddleware(logger)(s)
}
s = LoggingMiddleware(logger)(s)
s = RecoveringMiddleware(logger)(s)
return s
}
......@@ -302,39 +302,11 @@ func ProtoToPtrItemsFilter(protoFilter *itemspb.Filter) (*items.Filter, error) {
}
func PtrServicesFindOptionsToProto(options *services.FindOptions) (*common.FindOptions, error) {
if options == nil {
return nil, nil
}
return &common.FindOptions{
Sort: options.Sort,
PageNum: int32(options.PageNum),
PageSize: int32(options.PageSize),
Offset: int32(options.Offset),
Limit: int32(options.Limit),
Fields: options.Fields,
ExcludeFields: options.ExcludeFields,
}, nil
return services.FindOptionsToPB(options), nil
}
func ProtoToPtrServicesFindOptions(protoOptions *common.FindOptions) (*services.FindOptions, error) {
if protoOptions == nil {
return nil, nil
}
return &services.FindOptions{
SortOptions: services.SortOptions{
Sort: protoOptions.Sort,
},
PaginationOptions: services.PaginationOptions{
PageNum: int(protoOptions.PageNum),
PageSize: int(protoOptions.PageSize),
Offset: int(protoOptions.Offset),
Limit: int(protoOptions.Limit),
},
FieldOptions: services.FieldOptions{
Fields: protoOptions.Fields,
ExcludeFields: protoOptions.ExcludeFields,
},
}, nil
return services.FindOptionsFromPB(protoOptions), nil
}
func ListPtrItemsItemToProto(itms []*items.Item) ([]*itemspb.Item, error) {
......
......@@ -104,11 +104,18 @@ func PtrServicesFindOptionsToProto(opts *options.FindOptions) (*pb.FindOptions,
if opts == nil {
return nil, nil
}
return &pb.FindOptions{
fo := &pb.FindOptions{
Sort: opts.Sort,
PageNum: int32(opts.PageNum),
PageSize: int32(opts.PageSize),
}, nil
PageSize: int32(opts.Limit),
}
if opts.Limit != 0 {
// Потенциальная ошибка если offset не кратен limit
fo.PageNum = int32(opts.Offset / opts.Limit)
}
return fo, nil
}
func ProtoToPtrServicesFindOptions(protoOpts *pb.FindOptions) (*options.FindOptions, error) {
......@@ -120,8 +127,8 @@ func ProtoToPtrServicesFindOptions(protoOpts *pb.FindOptions) (*options.FindOpti
Sort: protoOpts.Sort,
},
PaginationOptions: options.PaginationOptions{
PageNum: int(protoOpts.PageNum),
PageSize: int(protoOpts.PageSize),
Limit: int(protoOpts.PageSize),
Offset: int(protoOpts.PageNum * protoOpts.PageSize),
},
}, nil
}
......
package items
import "context"
type FindResultDummy struct {
Items []*Item
Total int
Error error
}
type Dummy struct {
Items
FindResult *FindResultDummy
}
func (d *Dummy) Find(_ context.Context, _, _, _ string, _ *Filter, _ ...*FindOptions) ([]*Item, int, error) {
return d.FindResult.Items, d.FindResult.Total, d.FindResult.Error
}
......@@ -7,11 +7,14 @@ import (
)
const (
EventCreateItem = "create_item"
EventUpdateItem = "update_item"
EventPublishItem = "publish_item"
EventUnpublishItem = "unpublish_item"
EventDeleteItem = "delete_item"
EventItemCreate = "create_item"
EventItemUpdate = "update_item"
EventItemPublish = "publish_item"
EventItemUnpublish = "unpublish_item"
EventItemDelete = "delete_item"
EventItemUndelete = "item_undelete"
EventItemArchive = "item_archive"
EventItemUnarchive = "item_unarchive"
DefaultEventSubject = "content.{{.EventType}}.{{.SpaceID}}.{{.EnvID}}.{{.CollectionID}}.{{.ItemID}}"
)
......
// Code generated by gowrap. DO NOT EDIT.
// template: ../../../assets/templates/middleware/access_log.tmpl
// gowrap: http://github.com/hexdigest/gowrap
package middleware
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/items -i Items -t ../../../assets/templates/middleware/access_log.tmpl -o access_logging_middleware.go -l ""
import (
"context"
"time"
"git.perx.ru/perxis/perxis-go/pkg/auth"
"git.perx.ru/perxis/perxis-go/pkg/items"
"git.perx.ru/perxis/perxis-go/pkg/schema"
"go.uber.org/zap"
)
// accessLoggingMiddleware implements items.Items that is instrumented with logging
type accessLoggingMiddleware struct {
logger *zap.Logger
next items.Items
}
// AccessLoggingMiddleware instruments an implementation of the items.Items with simple logging
func AccessLoggingMiddleware(logger *zap.Logger) Middleware {
return func(next items.Items) items.Items {
return &accessLoggingMiddleware{
next: next,
logger: logger,
}
}
}
func (m *accessLoggingMiddleware) Aggregate(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.AggregateOptions) (result map[string]interface{}, err error) {
begin := time.Now()
m.logger.Debug("Aggregate.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("filter", filter),
zap.Reflect("options", options),
)
result, err = m.next.Aggregate(ctx, spaceId, envId, collectionId, filter, options...)
m.logger.Debug("Aggregate.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("result", result),
zap.Error(err),
)
return result, err
}
func (m *accessLoggingMiddleware) AggregatePublished(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.AggregatePublishedOptions) (result map[string]interface{}, err error) {
begin := time.Now()
m.logger.Debug("AggregatePublished.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("filter", filter),
zap.Reflect("options", options),
)
result, err = m.next.AggregatePublished(ctx, spaceId, envId, collectionId, filter, options...)
m.logger.Debug("AggregatePublished.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("result", result),
zap.Error(err),
)
return result, err
}
func (m *accessLoggingMiddleware) Archive(ctx context.Context, item *items.Item, options ...*items.ArchiveOptions) (err error) {
begin := time.Now()
m.logger.Debug("Archive.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Archive(ctx, item, options...)
m.logger.Debug("Archive.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Create(ctx context.Context, item *items.Item, opts ...*items.CreateOptions) (created *items.Item, err error) {
begin := time.Now()
m.logger.Debug("Create.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("opts", opts),
)
created, err = m.next.Create(ctx, item, opts...)
m.logger.Debug("Create.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("created", created),
zap.Error(err),
)
return created, err
}
func (m *accessLoggingMiddleware) Delete(ctx context.Context, item *items.Item, options ...*items.DeleteOptions) (err error) {
begin := time.Now()
m.logger.Debug("Delete.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Delete(ctx, item, options...)
m.logger.Debug("Delete.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Find(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.FindOptions) (items []*items.Item, total int, err error) {
begin := time.Now()
m.logger.Debug("Find.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("filter", filter),
zap.Reflect("options", options),
)
items, total, err = m.next.Find(ctx, spaceId, envId, collectionId, filter, options...)
m.logger.Debug("Find.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("items", items),
zap.Reflect("total", total),
zap.Error(err),
)
return items, total, err
}
func (m *accessLoggingMiddleware) FindArchived(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.FindArchivedOptions) (items []*items.Item, total int, err error) {
begin := time.Now()
m.logger.Debug("FindArchived.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("filter", filter),
zap.Reflect("options", options),
)
items, total, err = m.next.FindArchived(ctx, spaceId, envId, collectionId, filter, options...)
m.logger.Debug("FindArchived.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("items", items),
zap.Reflect("total", total),
zap.Error(err),
)
return items, total, err
}
func (m *accessLoggingMiddleware) FindPublished(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.FindPublishedOptions) (items []*items.Item, total int, err error) {
begin := time.Now()
m.logger.Debug("FindPublished.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("filter", filter),
zap.Reflect("options", options),
)
items, total, err = m.next.FindPublished(ctx, spaceId, envId, collectionId, filter, options...)
m.logger.Debug("FindPublished.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("items", items),
zap.Reflect("total", total),
zap.Error(err),
)
return items, total, err
}
func (m *accessLoggingMiddleware) Get(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, options ...*items.GetOptions) (item *items.Item, err error) {
begin := time.Now()
m.logger.Debug("Get.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("itemId", itemId),
zap.Reflect("options", options),
)
item, err = m.next.Get(ctx, spaceId, envId, collectionId, itemId, options...)
m.logger.Debug("Get.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("item", item),
zap.Error(err),
)
return item, err
}
func (m *accessLoggingMiddleware) GetPublished(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, options ...*items.GetPublishedOptions) (item *items.Item, err error) {
begin := time.Now()
m.logger.Debug("GetPublished.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("itemId", itemId),
zap.Reflect("options", options),
)
item, err = m.next.GetPublished(ctx, spaceId, envId, collectionId, itemId, options...)
m.logger.Debug("GetPublished.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("item", item),
zap.Error(err),
)
return item, err
}
func (m *accessLoggingMiddleware) GetRevision(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, revisionId string, options ...*items.GetRevisionOptions) (item *items.Item, err error) {
begin := time.Now()
m.logger.Debug("GetRevision.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("itemId", itemId),
zap.Reflect("revisionId", revisionId),
zap.Reflect("options", options),
)
item, err = m.next.GetRevision(ctx, spaceId, envId, collectionId, itemId, revisionId, options...)
m.logger.Debug("GetRevision.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("item", item),
zap.Error(err),
)
return item, err
}
func (m *accessLoggingMiddleware) Introspect(ctx context.Context, item *items.Item, opts ...*items.IntrospectOptions) (itm *items.Item, sch *schema.Schema, err error) {
begin := time.Now()
m.logger.Debug("Introspect.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("opts", opts),
)
itm, sch, err = m.next.Introspect(ctx, item, opts...)
m.logger.Debug("Introspect.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("itm", itm),
zap.Reflect("sch", sch),
zap.Error(err),
)
return itm, sch, err
}
func (m *accessLoggingMiddleware) ListRevisions(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, options ...*items.ListRevisionsOptions) (items []*items.Item, err error) {
begin := time.Now()
m.logger.Debug("ListRevisions.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("spaceId", spaceId),
zap.Reflect("envId", envId),
zap.Reflect("collectionId", collectionId),
zap.Reflect("itemId", itemId),
zap.Reflect("options", options),
)
items, err = m.next.ListRevisions(ctx, spaceId, envId, collectionId, itemId, options...)
m.logger.Debug("ListRevisions.Response",
zap.Duration("time", time.Since(begin)),
zap.Reflect("items", items),
zap.Error(err),
)
return items, err
}
func (m *accessLoggingMiddleware) Publish(ctx context.Context, item *items.Item, options ...*items.PublishOptions) (err error) {
begin := time.Now()
m.logger.Debug("Publish.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Publish(ctx, item, options...)
m.logger.Debug("Publish.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Unarchive(ctx context.Context, item *items.Item, options ...*items.UnarchiveOptions) (err error) {
begin := time.Now()
m.logger.Debug("Unarchive.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Unarchive(ctx, item, options...)
m.logger.Debug("Unarchive.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Undelete(ctx context.Context, item *items.Item, options ...*items.UndeleteOptions) (err error) {
begin := time.Now()
m.logger.Debug("Undelete.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Undelete(ctx, item, options...)
m.logger.Debug("Undelete.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Unpublish(ctx context.Context, item *items.Item, options ...*items.UnpublishOptions) (err error) {
begin := time.Now()
m.logger.Debug("Unpublish.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Unpublish(ctx, item, options...)
m.logger.Debug("Unpublish.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
func (m *accessLoggingMiddleware) Update(ctx context.Context, item *items.Item, options ...*items.UpdateOptions) (err error) {
begin := time.Now()
m.logger.Debug("Update.Request",
zap.Reflect("principal", auth.GetPrincipal(ctx)),
zap.Reflect("item", item),
zap.Reflect("options", options),
)
err = m.next.Update(ctx, item, options...)
m.logger.Debug("Update.Response",
zap.Duration("time", time.Since(begin)),
zap.Error(err),
)
return err
}
// Code generated by gowrap. DO NOT EDIT.
// template: ../../../assets/templates/middleware/error_log
// gowrap: http://github.com/hexdigest/gowrap
package middleware
//go:generate gowrap gen -p git.perx.ru/perxis/perxis-go/pkg/items -i Items -t ../../../assets/templates/middleware/error_log -o error_logging_middleware.go -l ""
import (
"context"
"git.perx.ru/perxis/perxis-go/pkg/items"
"git.perx.ru/perxis/perxis-go/pkg/schema"
"go.uber.org/zap"
)
// errorLoggingMiddleware implements items.Items that is instrumented with logging
type errorLoggingMiddleware struct {
logger *zap.Logger
next items.Items
}
// ErrorLoggingMiddleware instruments an implementation of the items.Items with simple logging
func ErrorLoggingMiddleware(logger *zap.Logger) Middleware {
return func(next items.Items) items.Items {
return &errorLoggingMiddleware{
next: next,
logger: logger,
}
}
}
func (m *errorLoggingMiddleware) Aggregate(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.AggregateOptions) (result map[string]interface{}, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Aggregate(ctx, spaceId, envId, collectionId, filter, options...)
}
func (m *errorLoggingMiddleware) AggregatePublished(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.AggregatePublishedOptions) (result map[string]interface{}, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.AggregatePublished(ctx, spaceId, envId, collectionId, filter, options...)
}
func (m *errorLoggingMiddleware) Archive(ctx context.Context, item *items.Item, options ...*items.ArchiveOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Archive(ctx, item, options...)
}
func (m *errorLoggingMiddleware) Create(ctx context.Context, item *items.Item, opts ...*items.CreateOptions) (created *items.Item, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Create(ctx, item, opts...)
}
func (m *errorLoggingMiddleware) Delete(ctx context.Context, item *items.Item, options ...*items.DeleteOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Delete(ctx, item, options...)
}
func (m *errorLoggingMiddleware) Find(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.FindOptions) (items []*items.Item, total int, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Find(ctx, spaceId, envId, collectionId, filter, options...)
}
func (m *errorLoggingMiddleware) FindArchived(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.FindArchivedOptions) (items []*items.Item, total int, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.FindArchived(ctx, spaceId, envId, collectionId, filter, options...)
}
func (m *errorLoggingMiddleware) FindPublished(ctx context.Context, spaceId string, envId string, collectionId string, filter *items.Filter, options ...*items.FindPublishedOptions) (items []*items.Item, total int, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.FindPublished(ctx, spaceId, envId, collectionId, filter, options...)
}
func (m *errorLoggingMiddleware) Get(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, options ...*items.GetOptions) (item *items.Item, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Get(ctx, spaceId, envId, collectionId, itemId, options...)
}
func (m *errorLoggingMiddleware) GetPublished(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, options ...*items.GetPublishedOptions) (item *items.Item, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.GetPublished(ctx, spaceId, envId, collectionId, itemId, options...)
}
func (m *errorLoggingMiddleware) GetRevision(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, revisionId string, options ...*items.GetRevisionOptions) (item *items.Item, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.GetRevision(ctx, spaceId, envId, collectionId, itemId, revisionId, options...)
}
func (m *errorLoggingMiddleware) Introspect(ctx context.Context, item *items.Item, opts ...*items.IntrospectOptions) (itm *items.Item, sch *schema.Schema, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Introspect(ctx, item, opts...)
}
func (m *errorLoggingMiddleware) ListRevisions(ctx context.Context, spaceId string, envId string, collectionId string, itemId string, options ...*items.ListRevisionsOptions) (items []*items.Item, err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.ListRevisions(ctx, spaceId, envId, collectionId, itemId, options...)
}
func (m *errorLoggingMiddleware) Publish(ctx context.Context, item *items.Item, options ...*items.PublishOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Publish(ctx, item, options...)
}
func (m *errorLoggingMiddleware) Unarchive(ctx context.Context, item *items.Item, options ...*items.UnarchiveOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Unarchive(ctx, item, options...)
}
func (m *errorLoggingMiddleware) Undelete(ctx context.Context, item *items.Item, options ...*items.UndeleteOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Undelete(ctx, item, options...)
}
func (m *errorLoggingMiddleware) Unpublish(ctx context.Context, item *items.Item, options ...*items.UnpublishOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Unpublish(ctx, item, options...)
}
func (m *errorLoggingMiddleware) Update(ctx context.Context, item *items.Item, options ...*items.UpdateOptions) (err error) {
logger := m.logger
defer func() {
if err != nil {
logger.Warn("response error", zap.Error(err))
}
}()
return m.next.Update(ctx, item, options...)
}
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment