diff --git a/logging/context.go b/logging/context.go new file mode 100644 index 00000000..e43126cc --- /dev/null +++ b/logging/context.go @@ -0,0 +1,32 @@ +package logging + +import ( + "context" + "errors" + + "go.uber.org/zap" +) + +type contextKey struct{} + +var ErrLoggerNotSet = errors.New("logger not set in context") + +func SetLogger(ctx context.Context, logger *zap.Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} + +func GetLoggerMaybe(ctx context.Context) (*zap.Logger, error) { + logger, ok := ctx.Value(contextKey{}).(*zap.Logger) + if !ok { + return nil, ErrLoggerNotSet + } + return logger, nil +} + +func GetLogger(ctx context.Context) *zap.Logger { + logger, err := GetLoggerMaybe(ctx) + if err != nil { + panic(err) + } + return logger +} diff --git a/logging/load.go b/logging/load.go new file mode 100644 index 00000000..b67937f2 --- /dev/null +++ b/logging/load.go @@ -0,0 +1,36 @@ +package logging + +import ( + "errors" + "os" + + "go.uber.org/zap" +) + +type Mode string + +const ( + Development Mode = "development" + Production Mode = "production" +) + +var ErrUnknownMode = errors.New("unknown mode") + +func Load(mode Mode) (*zap.Logger, error) { + switch mode { + case Development: + return zap.NewDevelopment() + case Production: + return zap.NewProduction() + default: + return nil, ErrUnknownMode + } +} + +func ModeFromEnv(varName string) Mode { + // TODO: strconv.ParseBool を使う + if os.Getenv(varName) != "" { + return Development + } + return Production +} diff --git a/main.go b/main.go index 78443b98..6e991455 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "os" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "github.com/traPtitech/Jomon/router" "github.com/traPtitech/Jomon/storage" @@ -41,28 +42,23 @@ func main() { repo := model.NewEntRepository(client, strg) // Setup server - var logger *zap.Logger - if os.Getenv("IS_DEBUG_MODE") != "" { - logger, err = zap.NewDevelopment() - } else { - logger, err = zap.NewProduction() + logMode := logging.ModeFromEnv("IS_DEBUG_MODE") + logger, err := logging.Load(logMode) + if err != nil { + panic(err) } defer func() { if err := logger.Sync(); err != nil { panic(err) } }() - if err != nil { - panic(err) - } handlers := router.Handlers{ Repository: repo, Storage: strg, - Logger: logger, SessionName: "session", } - server := router.NewServer(handlers) + server := handlers.NewServer(logger) port := os.Getenv("PORT") if port == "" { diff --git a/model/admin_impl_test.go b/model/admin_impl_test.go index 5ac48115..45561119 100644 --- a/model/admin_impl_test.go +++ b/model/admin_impl_test.go @@ -1,17 +1,17 @@ package model import ( - "context" "testing" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/traPtitech/Jomon/testutil" "github.com/traPtitech/Jomon/testutil/random" ) func TestEntRepository_GetAdmins(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_admins") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -53,7 +53,7 @@ func TestEntRepository_GetAdmins(t *testing.T) { } func TestEntRepository_AddAdmins(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "add_admins") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -77,7 +77,7 @@ func TestEntRepository_AddAdmins(t *testing.T) { } func TestEntRepository_DeleteAdmins(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_admins") require.NoError(t, err) repo := NewEntRepository(client, storage) diff --git a/model/comment_impl_test.go b/model/comment_impl_test.go index c76c4137..7be9dbb5 100644 --- a/model/comment_impl_test.go +++ b/model/comment_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -14,7 +13,7 @@ import ( ) func TestEntRepository_GetComments(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_comments") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -83,7 +82,7 @@ func TestEntRepository_GetComments(t *testing.T) { } func TestEntRepository_CreateComment(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_comment") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -159,7 +158,7 @@ func TestEntRepository_CreateComment(t *testing.T) { } func TestEntRepository_UpdateComment(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_comment") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -285,7 +284,7 @@ func TestEntRepository_UpdateComment(t *testing.T) { } func TestEntRepository_DeleteComment(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_comment") require.NoError(t, err) repo := NewEntRepository(client, storage) diff --git a/model/file_impl_test.go b/model/file_impl_test.go index 8bda6143..ad13dfd4 100644 --- a/model/file_impl_test.go +++ b/model/file_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -14,14 +13,14 @@ import ( ) func TestEntRepository_CreateFile(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_file") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) var tags []*Tag var targets []*RequestTarget @@ -60,7 +59,7 @@ func TestEntRepository_CreateFile(t *testing.T) { t.Run("UnknownRequest", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo.CreateUser( ctx, @@ -82,7 +81,7 @@ func TestEntRepository_CreateFile(t *testing.T) { t.Run("MissingName", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) var tags []*Tag var targets []*RequestTarget @@ -109,14 +108,14 @@ func TestEntRepository_CreateFile(t *testing.T) { } func TestEntRepository_GetFile(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_file") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) var tags []*Tag var targets []*RequestTarget @@ -156,7 +155,7 @@ func TestEntRepository_GetFile(t *testing.T) { t.Run("UnknownFile", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) _, err = repo.GetFile(ctx, uuid.New()) assert.Error(t, err) @@ -164,14 +163,14 @@ func TestEntRepository_GetFile(t *testing.T) { } func TestEntRepository_DeleteFile(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_file") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) var tags []*Tag var targets []*RequestTarget @@ -207,7 +206,7 @@ func TestEntRepository_DeleteFile(t *testing.T) { t.Run("UnknownFile", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) err = repo.DeleteFile(ctx, uuid.New()) assert.Error(t, err) diff --git a/model/group_impl_test.go b/model/group_impl_test.go index 4969748f..38e7522e 100644 --- a/model/group_impl_test.go +++ b/model/group_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -14,7 +13,7 @@ import ( ) func TestEntRepository_GetGroups(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_groups") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -47,7 +46,7 @@ func TestEntRepository_GetGroups(t *testing.T) { } func TestEntRepository_GetGroup(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_group") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -76,7 +75,7 @@ func TestEntRepository_GetGroup(t *testing.T) { } func TestEntRepository_CreateGroup(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_group") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -131,7 +130,7 @@ func TestEntRepository_CreateGroup(t *testing.T) { } func TestEntRepository_UpdateGroup(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_group") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -227,7 +226,7 @@ func TestEntRepository_UpdateGroup(t *testing.T) { } func TestEntRepository_DeleteGroup(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_group") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -258,7 +257,7 @@ func TestEntRepository_DeleteGroup(t *testing.T) { } func TestEntRepository_GetMembers(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_members") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -306,7 +305,7 @@ func TestEntRepository_GetMembers(t *testing.T) { t.Run("Success2", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) budget := random.Numeric(t, 100000) group, err := repo.CreateGroup( ctx, @@ -322,7 +321,7 @@ func TestEntRepository_GetMembers(t *testing.T) { } func TestEntRepository_CreateMember(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_member") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -352,7 +351,7 @@ func TestEntRepository_CreateMember(t *testing.T) { t.Run("UnknownUser", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) budget := random.Numeric(t, 100000) group, err := repo.CreateGroup( ctx, @@ -367,7 +366,7 @@ func TestEntRepository_CreateMember(t *testing.T) { } func TestEntRepository_DeleteMember(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_member") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -397,7 +396,7 @@ func TestEntRepository_DeleteMember(t *testing.T) { } func TestEntRepository_GetOwners(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_owners") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -442,7 +441,7 @@ func TestEntRepository_GetOwners(t *testing.T) { t.Run("Success2", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) budget := random.Numeric(t, 100000) group, err := repo.CreateGroup( ctx, @@ -459,7 +458,7 @@ func TestEntRepository_GetOwners(t *testing.T) { // FIXME: これAddOwnersでは? func TestEntRepository_CreateOwner(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_owner") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -489,7 +488,7 @@ func TestEntRepository_CreateOwner(t *testing.T) { t.Run("UnknownUser", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) budget := random.Numeric(t, 100000) group, err := repo.CreateGroup( ctx, @@ -504,7 +503,7 @@ func TestEntRepository_CreateOwner(t *testing.T) { } func TestEntRepository_DeleteOwner(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_owner") require.NoError(t, err) repo := NewEntRepository(client, storage) diff --git a/model/request_impl_test.go b/model/request_impl_test.go index 643d6c50..08ea811c 100644 --- a/model/request_impl_test.go +++ b/model/request_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -31,7 +30,7 @@ func (rd *RequestDetail) toExpectedRequestResponse(t *testing.T) *RequestRespons } func TestEntRepository_GetRequests(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_requests") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -62,7 +61,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithSortCreatedAt", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -130,7 +129,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithReverseSortCreatedAt", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo2.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -198,7 +197,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithSortTitle", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo3.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -265,7 +264,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithReverseSortTitle", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo4.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -332,7 +331,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithQueryTarget", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo5.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -397,7 +396,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithQuerySince", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo6.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -459,7 +458,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithQueryUntil", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo7.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -522,7 +521,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithQueryStatus", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo8.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -591,7 +590,7 @@ func TestEntRepository_GetRequests(t *testing.T) { t.Run("SuccessWithQueryCreatedBy", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo9.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -649,7 +648,7 @@ func TestEntRepository_GetRequests(t *testing.T) { } func TestEntRepository_CreateRequest(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_request") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -665,7 +664,7 @@ func TestEntRepository_CreateRequest(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 40) content := random.AlphaNumeric(t, 100) user, err := repo.CreateUser( @@ -723,7 +722,7 @@ func TestEntRepository_CreateRequest(t *testing.T) { t.Run("UnknownUser", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 40) content := random.AlphaNumeric(t, 100) tag, err := repo2.CreateTag(ctx, random.AlphaNumeric(t, 20)) @@ -747,7 +746,7 @@ func TestEntRepository_CreateRequest(t *testing.T) { t.Run("UnknownTag", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 40) content := random.AlphaNumeric(t, 100) user, err := repo3.CreateUser( @@ -783,7 +782,7 @@ func TestEntRepository_CreateRequest(t *testing.T) { t.Run("UnknownGroup", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 40) content := random.AlphaNumeric(t, 100) user, err := repo4.CreateUser( @@ -816,7 +815,7 @@ func TestEntRepository_CreateRequest(t *testing.T) { } func TestEntRepository_GetRequest(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_request") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -826,7 +825,7 @@ func TestEntRepository_GetRequest(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -862,14 +861,14 @@ func TestEntRepository_GetRequest(t *testing.T) { t.Run("UnknownRequest", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) _, err := repo2.GetRequest(ctx, uuid.New()) assert.Error(t, err) }) } func TestEntRepository_UpdateRequest(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_request") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -888,7 +887,7 @@ func TestEntRepository_UpdateRequest(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -949,7 +948,7 @@ func TestEntRepository_UpdateRequest(t *testing.T) { t.Run("Success2", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo2.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -1011,7 +1010,7 @@ func TestEntRepository_UpdateRequest(t *testing.T) { t.Run("Success3", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo3.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -1072,7 +1071,7 @@ func TestEntRepository_UpdateRequest(t *testing.T) { t.Run("UnknownTag", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo4.CreateUser( ctx, random.AlphaNumeric(t, 20), @@ -1117,7 +1116,7 @@ func TestEntRepository_UpdateRequest(t *testing.T) { t.Run("UnknownGroup", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user, err := repo5.CreateUser( ctx, random.AlphaNumeric(t, 20), diff --git a/model/request_status_impl_test.go b/model/request_status_impl_test.go index f5eee7e2..0f64f9dd 100644 --- a/model/request_status_impl_test.go +++ b/model/request_status_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -14,7 +13,7 @@ import ( ) func TestEntRepository_CreateStatus(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_status") require.NoError(t, err) repo := NewEntRepository(client, storage) diff --git a/model/request_target_impl_test.go b/model/request_target_impl_test.go index c81210a2..ca4a08d2 100644 --- a/model/request_target_impl_test.go +++ b/model/request_target_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -13,7 +12,7 @@ import ( ) func TestEntRepository_GetRequestTargets(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_request_targets") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -89,7 +88,7 @@ func TestEntRepository_GetRequestTargets(t *testing.T) { } func TestEntRepository_createRequestTargets(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_request_targets") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -139,7 +138,7 @@ func TestEntRepository_createRequestTargets(t *testing.T) { } func TestEntRepository_deleteRequestTargets(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_request_targets") require.NoError(t, err) repo := NewEntRepository(client, storage) diff --git a/model/tag_impl_test.go b/model/tag_impl_test.go index d734d002..c8f04045 100644 --- a/model/tag_impl_test.go +++ b/model/tag_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -13,7 +12,7 @@ import ( ) func TestEntRepository_GetTags(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_tags") assert.NoError(t, err) repo := NewEntRepository(client, storage) @@ -46,7 +45,7 @@ func TestEntRepository_GetTags(t *testing.T) { } func TestEntRepository_CreateTag(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_tag") assert.NoError(t, err) repo := NewEntRepository(client, storage) @@ -79,7 +78,7 @@ func TestEntRepository_CreateTag(t *testing.T) { } func TestEntRepository_UpdateTag(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_tag") assert.NoError(t, err) repo := NewEntRepository(client, storage) @@ -130,7 +129,7 @@ func TestEntRepository_UpdateTag(t *testing.T) { } func TestEntRepository_DeleteTag(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "delete_tag") assert.NoError(t, err) repo := NewEntRepository(client, storage) diff --git a/model/transaction_detail_impl_test.go b/model/transaction_detail_impl_test.go index bc118967..0ad15a17 100644 --- a/model/transaction_detail_impl_test.go +++ b/model/transaction_detail_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -13,14 +12,14 @@ import ( ) func TestEntRepository_createTransactionDetail(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_transaction_detail") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) tx, err := client.Tx(ctx) require.NoError(t, err) defer func() { @@ -52,14 +51,14 @@ func TestEntRepository_createTransactionDetail(t *testing.T) { } func TestEntRepository_updateTransactionDetail(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_transaction_detail") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) tx, err := client.Tx(ctx) require.NoError(t, err) defer func() { diff --git a/model/transaction_impl_test.go b/model/transaction_impl_test.go index e9bd4795..145c6802 100644 --- a/model/transaction_impl_test.go +++ b/model/transaction_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -14,7 +13,7 @@ import ( ) func TestEntRepository_GetTransactions(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_transactions") require.NoError(t, err) repo := NewEntRepository(client, storage) @@ -177,7 +176,7 @@ func TestEntRepository_GetTransactions(t *testing.T) { t.Run("SuccessWithSortAmountDesc", func(t *testing.T) { err := dropAll(t, ctx, client) require.NoError(t, err) - ctx := context.Background() + ctx := testutil.NewContext(t) // Create user // nolint:contextcheck @@ -501,13 +500,13 @@ func TestEntRepository_GetTransactions(t *testing.T) { } func TestEntRepository_GetTransaction(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_transaction") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) // Create user user, err := repo.CreateUser( @@ -542,14 +541,14 @@ func TestEntRepository_GetTransaction(t *testing.T) { } func TestEntRepository_CreateTransaction(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_transaction") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) amount := random.Numeric(t, 100000) @@ -608,7 +607,7 @@ func TestEntRepository_CreateTransaction(t *testing.T) { t.Run("SuccessWithoutTags", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 20) amount := random.Numeric(t, 100000) @@ -660,7 +659,7 @@ func TestEntRepository_CreateTransaction(t *testing.T) { t.Run("SuccessWithoutGroup", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 20) amount := random.Numeric(t, 100000) @@ -711,7 +710,7 @@ func TestEntRepository_CreateTransaction(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) // Create Transactions title := random.AlphaNumeric(t, 20) @@ -739,7 +738,7 @@ func TestEntRepository_CreateTransaction(t *testing.T) { t.Run("SuccessWithNegativeAmount", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) // Create Transactions title := random.AlphaNumeric(t, 20) @@ -766,14 +765,14 @@ func TestEntRepository_CreateTransaction(t *testing.T) { } func TestEntRepository_UpdateTransaction(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_transaction") require.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) title := random.AlphaNumeric(t, 20) amount := random.Numeric(t, 100000) diff --git a/model/user_impl_test.go b/model/user_impl_test.go index 50be2632..a37df27a 100644 --- a/model/user_impl_test.go +++ b/model/user_impl_test.go @@ -1,7 +1,6 @@ package model import ( - "context" "testing" "time" @@ -13,7 +12,7 @@ import ( ) func TestEntRepository_GetUsers(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_user") assert.NoError(t, err) repo := NewEntRepository(client, storage) @@ -23,7 +22,7 @@ func TestEntRepository_GetUsers(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) got, err := repo.GetUsers(ctx) assert.NoError(t, err) @@ -32,7 +31,7 @@ func TestEntRepository_GetUsers(t *testing.T) { t.Run("Success2", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) user1, err := repo2.CreateUser(ctx, "user1", "user1", true) assert.NoError(t, err) @@ -53,14 +52,14 @@ func TestEntRepository_GetUsers(t *testing.T) { } func TestEntRepository_CreateUser(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "create_user") assert.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) name := random.AlphaNumeric(t, 20) dn := random.AlphaNumeric(t, 20) @@ -83,7 +82,7 @@ func TestEntRepository_CreateUser(t *testing.T) { t.Run("MissingName", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) name := "" dn := random.AlphaNumeric(t, 20) @@ -95,7 +94,7 @@ func TestEntRepository_CreateUser(t *testing.T) { } func TestEntRepository_GetUserByName(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_user_by_name") assert.NoError(t, err) repo := NewEntRepository(client, storage) @@ -105,7 +104,7 @@ func TestEntRepository_GetUserByName(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) name := random.AlphaNumeric(t, 20) dn := random.AlphaNumeric(t, 20) admin := random.Numeric(t, 2) == 1 @@ -121,14 +120,14 @@ func TestEntRepository_GetUserByName(t *testing.T) { t.Run("UnknownName", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) _, err = repo2.GetUserByName(ctx, random.AlphaNumeric(t, 20)) assert.Error(t, err) }) } func TestEntRepository_GetUserByID(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "get_user_by_id") assert.NoError(t, err) repo := NewEntRepository(client, storage) @@ -138,7 +137,7 @@ func TestEntRepository_GetUserByID(t *testing.T) { t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) name := random.AlphaNumeric(t, 20) dn := random.AlphaNumeric(t, 20) admin := random.Numeric(t, 2) == 1 @@ -154,21 +153,21 @@ func TestEntRepository_GetUserByID(t *testing.T) { t.Run("UnknownUserID", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) _, err := repo2.GetUserByID(ctx, uuid.New()) assert.Error(t, err) }) } func TestEntRepository_UpdateUser(t *testing.T) { - ctx := context.Background() + ctx := testutil.NewContext(t) client, storage, err := setup(t, ctx, "update_user") assert.NoError(t, err) repo := NewEntRepository(client, storage) t.Run("Success", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) name := random.AlphaNumeric(t, 20) dn := random.AlphaNumeric(t, 20) @@ -196,7 +195,7 @@ func TestEntRepository_UpdateUser(t *testing.T) { t.Run("MissingName", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := testutil.NewContext(t) name := random.AlphaNumeric(t, 20) dn := random.AlphaNumeric(t, 20) diff --git a/router/admin.go b/router/admin.go index 0789f1cd..282d605f 100644 --- a/router/admin.go +++ b/router/admin.go @@ -7,15 +7,17 @@ import ( "github.com/labstack/echo/v4" "github.com/samber/lo" "github.com/traPtitech/Jomon/ent" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "go.uber.org/zap" ) func (h Handlers) GetAdmins(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) admins, err := h.Repository.GetAdmins(ctx) if err != nil { - h.Logger.Error("failed to get admins from repository", zap.Error(err)) + logger.Error("failed to get admins from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -27,20 +29,22 @@ func (h Handlers) GetAdmins(c echo.Context) error { } func (h Handlers) PostAdmins(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var admin []uuid.UUID if err := c.Bind(&admin); err != nil { - h.Logger.Info("failed to get admin id from request", zap.Error(err)) + logger.Info("failed to get admin id from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() err := h.Repository.AddAdmins(ctx, admin) if err != nil { if ent.IsConstraintError(err) { - h.Logger.Info("constraint error while adding admin in repository", zap.Error(err)) + logger.Info("constraint error while adding admin in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - h.Logger.Error("failed to add admin in repository", zap.Error(err)) + logger.Error("failed to add admin in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -48,16 +52,18 @@ func (h Handlers) PostAdmins(c echo.Context) error { } func (h Handlers) DeleteAdmins(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var admin []uuid.UUID if err := c.Bind(&admin); err != nil { - h.Logger.Info("failed to get admin id from request", zap.Error(err)) + logger.Info("failed to get admin id from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() err := h.Repository.DeleteAdmins(ctx, admin) if err != nil { - h.Logger.Error("failed to delete admin from repository", zap.Error(err)) + logger.Error("failed to delete admin from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } diff --git a/router/auth.go b/router/auth.go index e67626bf..f377daee 100644 --- a/router/auth.go +++ b/router/auth.go @@ -13,6 +13,7 @@ import ( "github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v4" "github.com/traPtitech/Jomon/ent" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "github.com/traPtitech/Jomon/service" "go.uber.org/zap" @@ -30,6 +31,9 @@ type AuthResponse struct { } func (h Handlers) AuthCallback(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + code := c.QueryParam("code") if len(code) == 0 { return echo.NewHTTPError(http.StatusBadRequest, "code is required") @@ -37,7 +41,7 @@ func (h Handlers) AuthCallback(c echo.Context) error { sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -56,28 +60,27 @@ func (h Handlers) AuthCallback(c echo.Context) error { res, err := service.RequestAccessToken(code, codeVerifier) if err != nil { - h.Logger.Error("failed to get access token", zap.Error(err)) + logger.Error("failed to get access token", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } u, err := service.FetchTraQUserInfo(res.AccessToken) if err != nil { - h.Logger.Error("failed to fetch traQ user info", zap.Error(err)) + logger.Error("failed to fetch traQ user info", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } var modelUser *model.User - modelUser, err = h.Repository.GetUserByName(c.Request().Context(), u.Name) + modelUser, err = h.Repository.GetUserByName(ctx, u.Name) if err != nil { if ent.IsNotFound(err) { - modelUser, err = h.Repository.CreateUser( - c.Request().Context(), u.Name, u.DisplayName, false) + modelUser, err = h.Repository.CreateUser(ctx, u.Name, u.DisplayName, false) if err != nil { - h.Logger.Error("failed to create user", zap.Error(err)) + logger.Error("failed to create user", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } } else { - h.Logger.Error("failed to get user by name", zap.Error(err)) + logger.Error("failed to get user by name", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } } @@ -92,7 +95,7 @@ func (h Handlers) AuthCallback(c echo.Context) error { sess.Values[sessionUserKey] = user if err = sess.Save(c.Request(), c.Response()); err != nil { - h.Logger.Error("failed to save session", zap.Error(err)) + logger.Error("failed to save session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -100,9 +103,12 @@ func (h Handlers) AuthCallback(c echo.Context) error { } func (h Handlers) GeneratePKCE(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -124,7 +130,7 @@ func (h Handlers) GeneratePKCE(c echo.Context) error { err = sess.Save(c.Request(), c.Response()) if err != nil { - h.Logger.Error("failed to save session", zap.Error(err)) + logger.Error("failed to save session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } // nolint:lll diff --git a/router/file.go b/router/file.go index a3ec7cd1..7a5c9cab 100644 --- a/router/file.go +++ b/router/file.go @@ -9,6 +9,7 @@ import ( "github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v4" "github.com/traPtitech/Jomon/ent" + "github.com/traPtitech/Jomon/logging" "go.uber.org/zap" ) @@ -35,37 +36,40 @@ var acceptedMimeTypes = map[string]bool{ } func (h Handlers) PostFile(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + form, err := c.MultipartForm() if err != nil { - h.Logger.Error("failed to parse request as multipart/form-data", zap.Error(err)) + logger.Error("failed to parse request as multipart/form-data", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } files, ok := form.File["file"] if !ok || len(files) != 1 { - h.Logger.Info("could not find field `file` in request, or its length is not 1") + logger.Info("could not find field `file` in request, or its length is not 1") return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid file")) } reqfile := files[0] names, ok := form.Value["name"] if !ok || len(names) != 1 { - h.Logger.Info("could not find field `name` in request, or its length is not 1") + logger.Info("could not find field `name` in request, or its length is not 1") return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid file name")) } name := names[0] requestIDs, ok := form.Value["request_id"] if !ok || len(requestIDs) != 1 { - h.Logger.Info("could not find field `request_id` in request, or its length is not 1") + logger.Info("could not find field `request_id` in request, or its length is not 1") return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid file request id")) } requestID, err := uuid.Parse(requestIDs[0]) if err != nil { - h.Logger.Info("could not parse request_id as UUID", zap.Error(err)) + logger.Info("could not parse request_id as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } mimetype := reqfile.Header.Get(echo.HeaderContentType) if !acceptedMimeTypes[mimetype] { - h.Logger.Info("requested unsupported mime type", zap.String("mime-type", mimetype)) + logger.Info("requested unsupported mime type", zap.String("mime-type", mimetype)) return echo.NewHTTPError( http.StatusUnsupportedMediaType, fmt.Errorf("unsupported media type")) @@ -73,7 +77,7 @@ func (h Handlers) PostFile(c echo.Context) error { src, err := reqfile.Open() if err != nil { - h.Logger.Error("failed to open requested file", zap.Error(err)) + logger.Error("failed to open requested file", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } defer src.Close() @@ -81,26 +85,25 @@ func (h Handlers) PostFile(c echo.Context) error { // get create user sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, ok := sess.Values[sessionUserKey].(User) if !ok { - h.Logger.Error("failed to parse stored session as user info") + logger.Error("failed to parse stored session as user info") return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("invalid user")) } - ctx := c.Request().Context() file, err := h.Repository.CreateFile(ctx, name, mimetype, requestID, user.ID) if err != nil { - h.Logger.Error("failed to create file in repository", zap.Error(err)) + logger.Error("failed to create file in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } err = h.Storage.Save(file.ID.String(), src) if err != nil { - h.Logger.Error("failed to save file id in storage", zap.Error(err)) + logger.Error("failed to save file id in storage", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -108,20 +111,22 @@ func (h Handlers) PostFile(c echo.Context) error { } func (h Handlers) GetFile(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + fileID, err := uuid.Parse(c.Param("fileID")) if err != nil { - h.Logger.Error("could not parse query parameter `fileID` as UUID", zap.Error(err)) + logger.Error("could not parse query parameter `fileID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() file, err := h.Repository.GetFile(ctx, fileID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info("could not find file in repository", zap.String("ID", fileID.String())) + logger.Info("could not find file in repository", zap.String("ID", fileID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get file from repository", zap.Error(err)) + logger.Error("failed to get file from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -131,11 +136,11 @@ func (h Handlers) GetFile(c echo.Context) error { if im != "" { imt, err := http.ParseTime(im) if err != nil { - h.Logger.Info("could not parse time in request header", zap.Error(err)) + logger.Info("could not parse time in request header", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if modifiedAt.Before(imt) || modifiedAt.Equal(imt) { - h.Logger.Info( + logger.Info( "content is not modified since the last request", zap.String("ID", fileID.String()), zap.Time("If-Modified-Since", imt)) @@ -145,7 +150,7 @@ func (h Handlers) GetFile(c echo.Context) error { f, err := h.Storage.Open(fileID.String()) if err != nil { - h.Logger.Error( + logger.Error( "failed to open file in storage", zap.String("ID", fileID.String()), zap.Error(err)) @@ -160,20 +165,22 @@ func (h Handlers) GetFile(c echo.Context) error { } func (h Handlers) GetFileMeta(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + fileID, err := uuid.Parse(c.Param("fileID")) if err != nil { - h.Logger.Info("could not parse query parameter `fileID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `fileID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() file, err := h.Repository.GetFile(ctx, fileID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info("could not find file in repository", zap.String("ID", fileID.String())) + logger.Info("could not find file in repository", zap.String("ID", fileID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get file from repository", zap.Error(err)) + logger.Error("failed to get file from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -187,26 +194,28 @@ func (h Handlers) GetFileMeta(c echo.Context) error { } func (h Handlers) DeleteFile(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + fileID, err := uuid.Parse(c.Param("fileID")) if err != nil { - h.Logger.Info("could not parse query parameter `fileID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `fileID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() err = h.Repository.DeleteFile(ctx, fileID) if err != nil { if ent.IsConstraintError(err) { - h.Logger.Info("constraint error while deleting file", zap.Error(err)) + logger.Info("constraint error while deleting file", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - h.Logger.Error("failed to delete file in repository", zap.Error(err)) + logger.Error("failed to delete file in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } err = h.Storage.Delete(fileID.String()) if err != nil { - h.Logger.Error("failed to delete file in storage", zap.Error(err)) + logger.Error("failed to delete file in storage", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } diff --git a/router/group.go b/router/group.go index 419ad0a5..92740a47 100644 --- a/router/group.go +++ b/router/group.go @@ -9,6 +9,7 @@ import ( "github.com/labstack/echo/v4" "github.com/samber/lo" "github.com/traPtitech/Jomon/ent" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "go.uber.org/zap" ) @@ -57,9 +58,11 @@ type Member struct { // GetGroups GET /groups func (h Handlers) GetGroups(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + groups, err := h.Repository.GetGroups(ctx) if err != nil { - h.Logger.Error("failed to get groups from repository", zap.Error(err)) + logger.Error("failed to get groups from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -79,16 +82,18 @@ func (h Handlers) GetGroups(c echo.Context) error { // PostGroup POST /groups func (h Handlers) PostGroup(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var group Group if err := c.Bind(&group); err != nil { - h.Logger.Info("failed to get group from request", zap.Error(err)) + logger.Info("failed to get group from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() created, err := h.Repository.CreateGroup(ctx, group.Name, group.Description, group.Budget) if err != nil { - h.Logger.Error("failed to create group in repository", zap.Error(err)) + logger.Error("failed to create group in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -106,27 +111,29 @@ func (h Handlers) PostGroup(c echo.Context) error { // GetGroupDetail GET /groups/:groupID func (h Handlers) GetGroupDetail(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { - h.Logger.Info("received invalid UUID") + logger.Info("received invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } - ctx := c.Request().Context() group, err := h.Repository.GetGroup(ctx, groupID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not fin group in repository", zap.String("ID", groupID.String()), zap.Error(err)) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get group from repository", zap.Error(err)) + logger.Error("failed to get group from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } res := GroupDetail{ @@ -141,7 +148,7 @@ func (h Handlers) GetGroupDetail(c echo.Context) error { } owners, err := h.Repository.GetOwners(ctx, groupID) if err != nil { - h.Logger.Error("failed to get owners from repository", zap.Error(err)) + logger.Error("failed to get owners from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } res.Owners = lo.Map(owners, func(owner *model.Owner, _ int) *uuid.UUID { @@ -149,7 +156,7 @@ func (h Handlers) GetGroupDetail(c echo.Context) error { }) members, err := h.Repository.GetMembers(ctx, groupID) if err != nil { - h.Logger.Error("failed to get members from repository", zap.Error(err)) + logger.Error("failed to get members from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } res.Members = lo.Map(members, func(member *model.Member, indec int) *uuid.UUID { @@ -161,27 +168,29 @@ func (h Handlers) GetGroupDetail(c echo.Context) error { // PutGroup PUT /groups/:groupID func (h Handlers) PutGroup(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var group Group if err := c.Bind(&group); err != nil { - h.Logger.Info("could not get group from request", zap.Error(err)) + logger.Info("could not get group from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } - ctx := c.Request().Context() updated, err := h.Repository.UpdateGroup( ctx, groupID, group.Name, group.Description, group.Budget) if err != nil { - h.Logger.Error("failed to update group in repository", zap.Error(err)) + logger.Error("failed to update group in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -199,20 +208,22 @@ func (h Handlers) PutGroup(c echo.Context) error { // DeleteGroup DELETE /groups/:groupID func (h Handlers) DeleteGroup(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { - h.Logger.Info("received invalid UUID") + logger.Info("received invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } - ctx := c.Request().Context() err = h.Repository.DeleteGroup(ctx, groupID) if err != nil { - h.Logger.Error("failed to delete group from repository", zap.Error(err)) + logger.Error("failed to delete group from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -222,23 +233,25 @@ func (h Handlers) DeleteGroup(c echo.Context) error { // PostMember POST /groups/:groupID/members func (h Handlers) PostMember(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { - h.Logger.Info("received invalid UUID") + logger.Info("received invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } var member []uuid.UUID if err := c.Bind(&member); err != nil { - h.Logger.Info("could not get member id from request", zap.Error(err)) + logger.Info("could not get member id from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } added, err := h.Repository.AddMembers(ctx, groupID, member) if err != nil { - h.Logger.Error("failed to add member in repository", zap.Error(err)) + logger.Error("failed to add member in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } res := lo.Map(added, func(m *model.Member, _ int) *uuid.UUID { @@ -250,23 +263,25 @@ func (h Handlers) PostMember(c echo.Context) error { // DeleteMember DELETE /groups/:groupID/members func (h Handlers) DeleteMember(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { - h.Logger.Info("received invalid UUID") + logger.Info("received invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } var member []uuid.UUID if err := c.Bind(&member); err != nil { - h.Logger.Info("could not get member id from request", zap.Error(err)) + logger.Info("could not get member id from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } err = h.Repository.DeleteMembers(ctx, groupID, member) if err != nil { - h.Logger.Error("failed to delete member from repository", zap.Error(err)) + logger.Error("failed to delete member from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } return c.NoContent(http.StatusOK) @@ -275,27 +290,29 @@ func (h Handlers) DeleteMember(c echo.Context) error { // PostOwner POST /groups/:groupID/owners func (h Handlers) PostOwner(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var owners []uuid.UUID groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { - h.Logger.Info("received invalid UUID") + logger.Info("received invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } if err := c.Bind(&owners); err != nil { - h.Logger.Info("could not get owner id from request", zap.Error(err)) + logger.Info("could not get owner id from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } added, err := h.Repository.AddOwners(ctx, groupID, owners) if err != nil { if ent.IsConstraintError(err) { - h.Logger.Info("constraint error while adding owner in repository", zap.Error(err)) + logger.Info("constraint error while adding owner in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - h.Logger.Error("failed to add owner in repository", zap.Error(err)) + logger.Error("failed to add owner in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -309,28 +326,30 @@ func (h Handlers) PostOwner(c echo.Context) error { // DeleteOwner DELETE /groups/:groupID/owners func (h Handlers) DeleteOwner(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + groupID, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `groupID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if groupID == uuid.Nil { - h.Logger.Info("received invalid UUID") + logger.Info("received invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } var ownerIDs []uuid.UUID if err := c.Bind(&ownerIDs); err != nil { - h.Logger.Info("could not get owner id from request", zap.Error(err)) + logger.Info("could not get owner id from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } err = h.Repository.DeleteOwners(ctx, groupID, ownerIDs) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info("could not find owner in repository", zap.Error(err)) + logger.Info("could not find owner in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to delete owner from repository", zap.Error(err)) + logger.Error("failed to delete owner from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } diff --git a/router/middleware.go b/router/middleware.go index 44fe6e01..259e5e94 100644 --- a/router/middleware.go +++ b/router/middleware.go @@ -10,6 +10,7 @@ import ( "github.com/gorilla/sessions" "github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v4" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "go.uber.org/zap" "go.uber.org/zap/zapcore" @@ -22,55 +23,67 @@ const ( sessionFileCreatorKey = "request_creator" ) -// AccessLoggingMiddleware ですべてのエラーを出力する -func (h Handlers) AccessLoggingMiddleware(logger *zap.Logger) echo.MiddlewareFunc { +func (h Handlers) setLoggerMiddleware(logger *zap.Logger) echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { - start := time.Now() - err := next(c) - if err != nil { - c.Error(err) - } - stop := time.Now() - req := c.Request() - res := c.Response() - latency := strconv.FormatFloat(stop.Sub(start).Seconds(), 'f', 9, 64) + "s" - fields := []zapcore.Field{ - zap.String("requestMethod", req.Method), - zap.Int("status", res.Status), - zap.String("userAgent", req.UserAgent()), - zap.String("remoteIp", c.RealIP()), - zap.String("referer", req.Referer()), - zap.String("protocol", req.Proto), - zap.String("requestUrl", req.URL.String()), - zap.String("requestSize", req.Header.Get(echo.HeaderContentLength)), - zap.String("responseSize", strconv.FormatInt(res.Size, 10)), - zap.String("latency", latency), - } - httpCode := res.Status - switch { - case httpCode >= 500: - fields = append(fields, zap.Error(err)) - logger.Error("server error", fields...) - case httpCode >= 400: - fields = append(fields, zap.Error(err)) - logger.Warn("client error", fields...) - case httpCode >= 300: - logger.Info("redirect", fields...) - default: - logger.Info("success", fields...) - } - return nil + ctx := req.Context() + ctx = logging.SetLogger(ctx, logger) + c.SetRequest(req.WithContext(ctx)) + return next(c) + } + } +} + +// AccessLoggingMiddleware ですべてのエラーを出力する +func (h Handlers) AccessLoggingMiddleware(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + start := time.Now() + err := next(c) + if err != nil { + c.Error(err) + } + stop := time.Now() + + req := c.Request() + res := c.Response() + logger := logging.GetLogger(req.Context()) + latency := strconv.FormatFloat(stop.Sub(start).Seconds(), 'f', 9, 64) + "s" + fields := []zapcore.Field{ + zap.String("requestMethod", req.Method), + zap.Int("status", res.Status), + zap.String("userAgent", req.UserAgent()), + zap.String("remoteIp", c.RealIP()), + zap.String("referer", req.Referer()), + zap.String("protocol", req.Proto), + zap.String("requestUrl", req.URL.String()), + zap.String("requestSize", req.Header.Get(echo.HeaderContentLength)), + zap.String("responseSize", strconv.FormatInt(res.Size, 10)), + zap.String("latency", latency), + } + httpCode := res.Status + switch { + case httpCode >= 500: + fields = append(fields, zap.Error(err)) + logger.Error("server error", fields...) + case httpCode >= 400: + fields = append(fields, zap.Error(err)) + logger.Warn("client error", fields...) + case httpCode >= 300: + logger.Info("redirect", fields...) + default: + logger.Info("success", fields...) } + return nil } } func (h Handlers) CheckLoginMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -85,15 +98,16 @@ func (h Handlers) CheckLoginMiddleware(next echo.HandlerFunc) echo.HandlerFunc { func (h Handlers) CheckAdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, err := getUserInfo(sess) if err != nil { - h.Logger.Error("failed to get user info", zap.Error(err)) + logger.Error("failed to get user info", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -107,15 +121,16 @@ func (h Handlers) CheckAdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc { func (h Handlers) CheckRequestCreatorMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, err := getUserInfo(sess) if err != nil { - h.Logger.Error("failed to get user info", zap.Error(err)) + logger.Error("failed to get user info", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -135,15 +150,16 @@ func (h Handlers) CheckRequestCreatorMiddleware(next echo.HandlerFunc) echo.Hand func (h Handlers) CheckAdminOrRequestCreatorMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, err := getUserInfo(sess) if err != nil { - h.Logger.Error("failed to get user info", zap.Error(err)) + logger.Error("failed to get user info", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -163,21 +179,22 @@ func (h Handlers) CheckAdminOrRequestCreatorMiddleware(next echo.HandlerFunc) ec func (h Handlers) CheckAdminOrGroupOwnerMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, err := getUserInfo(sess) if err != nil { - h.Logger.Error("failed to get user info", zap.Error(err)) + logger.Error("failed to get user info", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } owners, ok := sess.Values[sessionOwnerKey].([]*model.Owner) if !ok { - h.Logger.Error("failed to get group owner", zap.Error(err)) + logger.Error("failed to get group owner", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, "session owner key is not set") } @@ -197,15 +214,16 @@ func (h Handlers) CheckAdminOrGroupOwnerMiddleware(next echo.HandlerFunc) echo.H func (h Handlers) CheckFileCreatorMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, err := getUserInfo(sess) if err != nil { - h.Logger.Error("failed to get user info", zap.Error(err)) + logger.Error("failed to get user info", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -252,28 +270,29 @@ func (h Handlers) CheckAdminOrFileCreatorMiddleware(next echo.HandlerFunc) echo. func (h Handlers) RetrieveGroupOwner() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } id, err := uuid.Parse(c.Param("groupID")) if err != nil { - h.Logger.Info("could not parse group_id as UUID", zap.Error(err)) + logger.Info("could not parse group_id as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } ctx := c.Request().Context() owners, err := h.Repository.GetOwners(ctx, id) if err != nil { - h.Logger.Error("failed to get owners from repository", zap.Error(err)) + logger.Error("failed to get owners from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } sess.Values[sessionOwnerKey] = owners if err = sess.Save(c.Request(), c.Response()); err != nil { - h.Logger.Error("failed to save session", zap.Error(err)) + logger.Error("failed to save session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -285,28 +304,29 @@ func (h Handlers) RetrieveGroupOwner() echo.MiddlewareFunc { func (h Handlers) RetrieveRequestCreator() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } id, err := uuid.Parse(c.Param("requestID")) if err != nil { - h.Logger.Info("could not parse request_id as UUID", zap.Error(err)) + logger.Info("could not parse request_id as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } ctx := c.Request().Context() request, err := h.Repository.GetRequest(ctx, id) if err != nil { - h.Logger.Error("failed to get request from repository", zap.Error(err)) + logger.Error("failed to get request from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } sess.Values[sessionRequestCreatorKey] = request.CreatedBy if err = sess.Save(c.Request(), c.Response()); err != nil { - h.Logger.Error("failed to save session", zap.Error(err)) + logger.Error("failed to save session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -318,28 +338,29 @@ func (h Handlers) RetrieveRequestCreator() echo.MiddlewareFunc { func (h Handlers) RetrieveFileCreator() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + logger := logging.GetLogger(c.Request().Context()) sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } id, err := uuid.Parse(c.Param("fileID")) if err != nil { - h.Logger.Info("could not parse file_id as UUID", zap.Error(err)) + logger.Info("could not parse file_id as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } ctx := c.Request().Context() file, err := h.Repository.GetFile(ctx, id) if err != nil { - h.Logger.Error("failed to get file from repository", zap.Error(err)) + logger.Error("failed to get file from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } sess.Values[sessionFileCreatorKey] = file.CreatedBy if err = sess.Save(c.Request(), c.Response()); err != nil { - h.Logger.Error("failed to save session", zap.Error(err)) + logger.Error("failed to save session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } diff --git a/router/request.go b/router/request.go index 56a3dda3..ce22c881 100644 --- a/router/request.go +++ b/router/request.go @@ -12,6 +12,7 @@ import ( "github.com/labstack/echo/v4" "github.com/samber/lo" "github.com/traPtitech/Jomon/ent" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "github.com/traPtitech/Jomon/service" "go.uber.org/zap" @@ -116,6 +117,8 @@ type TargetOverview struct { func (h Handlers) GetRequests(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var sort *string if s := c.QueryParam("sort"); s != "" { sort = &s @@ -135,7 +138,7 @@ func (h Handlers) GetRequests(c echo.Context) error { if c.QueryParam("target") != "" { t, err := uuid.Parse(c.QueryParam("target")) if err != nil { - h.Logger.Info("could not parse query parameter `target` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `target` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } target = &t @@ -144,7 +147,7 @@ func (h Handlers) GetRequests(c echo.Context) error { if c.QueryParam("since") != "" { s, err := service.StrToDate(c.QueryParam("since")) if err != nil { - h.Logger.Info("could not parse query parameter `since` as time.Time", zap.Error(err)) + logger.Info("could not parse query parameter `since` as time.Time", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } since = &s @@ -153,7 +156,7 @@ func (h Handlers) GetRequests(c echo.Context) error { if c.QueryParam("until") != "" { u, err := service.StrToDate(c.QueryParam("until")) if err != nil { - h.Logger.Info("could not parse query parameter `until` as time.Time", zap.Error(err)) + logger.Info("could not parse query parameter `until` as time.Time", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } until = &u @@ -162,11 +165,11 @@ func (h Handlers) GetRequests(c echo.Context) error { if limitQuery := c.QueryParam("limit"); limitQuery != "" { limitI, err := strconv.Atoi(limitQuery) if err != nil { - h.Logger.Info("could not parse limit as integer", zap.Error(err)) + logger.Info("could not parse limit as integer", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if limitI < 0 { - h.Logger.Info("received negative limit", zap.Int("limit", limitI)) + logger.Info("received negative limit", zap.Int("limit", limitI)) return echo.NewHTTPError( http.StatusBadRequest, fmt.Errorf("negative limit(=%d) is invalid", limitI), @@ -178,11 +181,11 @@ func (h Handlers) GetRequests(c echo.Context) error { if offsetQuery := c.QueryParam("offset"); offsetQuery != "" { offsetI, err := strconv.Atoi(offsetQuery) if err != nil { - h.Logger.Info("could not parse offset as integer", zap.Error(err)) + logger.Info("could not parse offset as integer", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if offsetI < 0 { - h.Logger.Info("received negative offset", zap.Int("offset", offsetI)) + logger.Info("received negative offset", zap.Int("offset", offsetI)) return echo.NewHTTPError( http.StatusBadRequest, fmt.Errorf("negative offset(=%d) is invalid", offsetI), @@ -204,7 +207,7 @@ func (h Handlers) GetRequests(c echo.Context) error { if c.QueryParam("created_by") != "" { u, err := uuid.Parse(c.QueryParam("created_by")) if err != nil { - h.Logger.Info("could not parse query parameter `created_by` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `created_by` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } cratedBy = &u @@ -224,7 +227,7 @@ func (h Handlers) GetRequests(c echo.Context) error { modelrequests, err := h.Repository.GetRequests(ctx, query) if err != nil { - h.Logger.Error("failed to get requests from repository", zap.Error(err)) + logger.Error("failed to get requests from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -291,15 +294,17 @@ func (h Handlers) PostRequest(c echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, err) } ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + tags := []*model.Tag{} for _, tagID := range req.Tags { tag, err := h.Repository.GetTag(ctx, *tagID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info("could not find tag in repository", zap.String("ID", tagID.String())) + logger.Info("could not find tag in repository", zap.String("ID", tagID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get tag from repository", zap.Error(err)) + logger.Error("failed to get tag from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } tags = append(tags, tag) @@ -315,12 +320,12 @@ func (h Handlers) PostRequest(c echo.Context) error { group, err = h.Repository.GetGroup(ctx, *req.Group) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find group in repository", zap.String("ID", req.Group.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get group from repository", zap.Error(err)) + logger.Error("failed to get group from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } } @@ -329,12 +334,12 @@ func (h Handlers) PostRequest(c echo.Context) error { req.Title, req.Content, tags, targets, group, req.CreatedBy) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find request in repository", zap.String("ID", req.CreatedBy.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to create request in repository", zap.Error(err)) + logger.Error("failed to create request in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } var resgroup *GroupOverview @@ -396,32 +401,34 @@ func (h Handlers) PostRequest(c echo.Context) error { } func (h Handlers) GetRequest(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + requestID, err := uuid.Parse(c.Param("requestID")) if err != nil { - h.Logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if requestID == uuid.Nil { - h.Logger.Info("invalid UUID") + logger.Info("invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } - ctx := c.Request().Context() request, err := h.Repository.GetRequest(ctx, requestID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find request in repository", zap.String("ID", requestID.String()), zap.Error(err)) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get request from repository", zap.Error(err)) + logger.Error("failed to get request from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } modelcomments, err := h.Repository.GetComments(ctx, requestID) if err != nil { - h.Logger.Error("failed to get comments from repository", zap.Error(err)) + logger.Error("failed to get comments from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } comments := lo.Map(modelcomments, func(modelcomment *model.Comment, _ int) *CommentDetail { @@ -495,20 +502,22 @@ func (h Handlers) GetRequest(c echo.Context) error { func (h Handlers) PutRequest(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var req PutRequest var err error requestID, err := uuid.Parse(c.Param("requestID")) if err != nil { - h.Logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if requestID == uuid.Nil { - h.Logger.Info("invalid UUID") + logger.Info("invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid UUID")) } if err = c.Bind(&req); err != nil { - h.Logger.Info("failed to get request from request", zap.Error(err)) + logger.Info("failed to get request from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } tags := []*model.Tag{} @@ -516,10 +525,10 @@ func (h Handlers) PutRequest(c echo.Context) error { tag, err := h.Repository.GetTag(ctx, *tagID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info("could not find tag in repository", zap.String("ID", tagID.String())) + logger.Info("could not find tag in repository", zap.String("ID", tagID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get tag from repository", zap.Error(err)) + logger.Error("failed to get tag from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } tags = append(tags, tag) @@ -535,12 +544,12 @@ func (h Handlers) PutRequest(c echo.Context) error { group, err = h.Repository.GetGroup(ctx, *req.Group) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find group in repository", zap.String("ID", req.Group.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get group from repository", zap.Error(err)) + logger.Error("failed to get group from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } } @@ -549,17 +558,17 @@ func (h Handlers) PutRequest(c echo.Context) error { requestID, req.Title, req.Content, tags, targets, group) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find request in repository", zap.String("ID", requestID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to update request in repository", zap.Error(err)) + logger.Error("failed to update request in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } modelcomments, err := h.Repository.GetComments(ctx, requestID) if err != nil { - h.Logger.Error("failed to get comments from repository", zap.Error(err)) + logger.Error("failed to get comments from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } comments := lo.Map(modelcomments, func(modelcomment *model.Comment, _ int) *CommentDetail { @@ -634,43 +643,45 @@ func (h Handlers) PutRequest(c echo.Context) error { } func (h Handlers) PostComment(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + requestID, err := uuid.Parse(c.Param("requestID")) if err != nil { - h.Logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if requestID == uuid.Nil { - h.Logger.Info("invalid UUID") + logger.Info("invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, err) } var req Comment if err := c.Bind(&req); err != nil { - h.Logger.Info("failed to get comment from request", zap.Error(err)) + logger.Info("failed to get comment from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, ok := sess.Values[sessionUserKey].(User) if !ok { - h.Logger.Info("could not find use in session") + logger.Info("could not find use in session") return echo.NewHTTPError(http.StatusUnauthorized, errors.New("sessionUser not found")) } - ctx := c.Request().Context() comment, err := h.Repository.CreateComment(ctx, req.Comment, requestID, user.ID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find request in repository", zap.String("ID", requestID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to create comment in repository", zap.Error(err)) + logger.Error("failed to create comment in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } res := &CommentDetail{ @@ -684,43 +695,45 @@ func (h Handlers) PostComment(c echo.Context) error { } func (h Handlers) PutStatus(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var req PutStatus var err error requestID, err := uuid.Parse(c.Param("requestID")) if err != nil { - h.Logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `requestID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if requestID == uuid.Nil { - h.Logger.Info("invalid UUID") + logger.Info("invalid UUID") return echo.NewHTTPError(http.StatusBadRequest, err) } sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } user, ok := sess.Values[sessionUserKey].(User) if !ok { - h.Logger.Info("could not find use in session") + logger.Info("could not find use in session") return echo.NewHTTPError(http.StatusForbidden, errors.New("sessionUser not found")) } if err = c.Bind(&req); err != nil { - h.Logger.Info("could not get status from request", zap.Error(err)) + logger.Info("could not get status from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() request, err := h.Repository.GetRequest(ctx, requestID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info( + logger.Info( "could not find request in repository", zap.String("ID", requestID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get request from repository", zap.Error(err)) + logger.Error("failed to get request from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -740,15 +753,15 @@ func (h Handlers) PutStatus(c echo.Context) error { u, err := h.Repository.GetUserByID(ctx, user.ID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Info("could not find user in repository", zap.String("ID", user.ID.String())) + logger.Info("could not find user in repository", zap.String("ID", user.ID.String())) return echo.NewHTTPError(http.StatusNotFound, err) } - h.Logger.Error("failed to get user from repository", zap.Error(err)) + logger.Error("failed to get user from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } if u.Admin { if !IsAbleAdminChangeState(req.Status, request.Status) { - h.Logger.Info("admin unable to change status") + logger.Info("admin unable to change status") err := fmt.Errorf( "admin unable to change %v to %v", request.Status.String(), req.Status.String()) @@ -757,14 +770,14 @@ func (h Handlers) PutStatus(c echo.Context) error { if req.Status == model.Submitted && request.Status == model.Accepted { targets, err := h.Repository.GetRequestTargets(ctx, requestID) if err != nil { - h.Logger.Error("failed to get request targets from repository", zap.Error(err)) + logger.Error("failed to get request targets from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } paid := lo.Reduce(targets, func(p bool, target *model.RequestTargetDetail, _ int) bool { return p || target.PaidAt != nil }, false) if paid { - h.Logger.Info("someone already paid") + logger.Info("someone already paid") return echo.NewHTTPError(http.StatusBadRequest, errors.New("someone already paid")) } } @@ -772,7 +785,7 @@ func (h Handlers) PutStatus(c echo.Context) error { if !u.Admin && user.ID == request.CreatedBy { if !IsAbleCreatorChangeStatus(req.Status, request.Status) { - h.Logger.Info("creator unable to change status") + logger.Info("creator unable to change status") err := fmt.Errorf( "creator unable to change %v to %v", request.Status.String(), req.Status.String()) @@ -781,21 +794,21 @@ func (h Handlers) PutStatus(c echo.Context) error { } if user.ID != request.CreatedBy && !u.Admin { - h.Logger.Info("use is not creator or admin") + logger.Info("use is not creator or admin") return echo.NewHTTPError(http.StatusForbidden) } // create status and comment: keep the two in this order created, err := h.Repository.CreateStatus(ctx, requestID, user.ID, req.Status) if err != nil { - h.Logger.Error("failed to create status in repository", zap.Error(err)) + logger.Error("failed to create status in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } var resComment CommentDetail if req.Comment != "" { comment, err := h.Repository.CreateComment(ctx, req.Comment, request.ID, user.ID) if err != nil { - h.Logger.Error("failed to create comment in repository", zap.Error(err)) + logger.Error("failed to create comment in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } resComment = CommentDetail{ diff --git a/router/router.go b/router/router.go index ca3a347f..696858c3 100644 --- a/router/router.go +++ b/router/router.go @@ -19,14 +19,14 @@ import ( type Handlers struct { Repository model.Repository Storage storage.Storage - Logger *zap.Logger SessionName string } -func NewServer(h Handlers) *echo.Echo { +func (h Handlers) NewServer(logger *zap.Logger) *echo.Echo { e := echo.New() e.Debug = os.Getenv("IS_DEBUG_MODE") != "" - e.Use(h.AccessLoggingMiddleware(h.Logger)) + e.Use(h.setLoggerMiddleware(logger)) + e.Use(h.AccessLoggingMiddleware) e.Use(middleware.Recover()) e.Use(middleware.Secure()) e.Use(session.Middleware(sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY"))))) diff --git a/router/router_test.go b/router/router_test.go index 10373336..01a1f7ae 100644 --- a/router/router_test.go +++ b/router/router_test.go @@ -12,7 +12,6 @@ import ( "github.com/traPtitech/Jomon/model/mock_model" "github.com/traPtitech/Jomon/testutil/random" "go.uber.org/mock/gomock" - "go.uber.org/zap" ) type MockRepository struct { @@ -70,10 +69,6 @@ type TestHandlers struct { } func NewTestHandlers(_ *testing.T, ctrl *gomock.Controller) (*TestHandlers, error) { - logger, err := zap.NewDevelopment() - if err != nil { - return nil, err - } gob.Register(User{}) repository := NewMockRepository(ctrl) storage := NewMockStorage(ctrl) @@ -83,7 +78,6 @@ func NewTestHandlers(_ *testing.T, ctrl *gomock.Controller) (*TestHandlers, erro Handlers{ Repository: repository, Storage: storage, - Logger: logger, SessionName: sessionName, }, repository, diff --git a/router/tag.go b/router/tag.go index 49c60366..34663a32 100644 --- a/router/tag.go +++ b/router/tag.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/labstack/echo/v4" "github.com/samber/lo" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "go.uber.org/zap" ) @@ -26,9 +27,11 @@ type TagOverview struct { func (h Handlers) GetTags(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + tags, err := h.Repository.GetTags(ctx) if err != nil { - h.Logger.Error("failed to get tags from repository", zap.Error(err)) + logger.Error("failed to get tags from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -45,16 +48,18 @@ func (h Handlers) GetTags(c echo.Context) error { } func (h Handlers) PostTag(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var tag Tag if err := c.Bind(&tag); err != nil { - h.Logger.Info("could not get tag from request", zap.Error(err)) + logger.Info("could not get tag from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() created, err := h.Repository.CreateTag(ctx, tag.Name) if err != nil { - h.Logger.Error("failed to create tag in repository", zap.Error(err)) + logger.Error("failed to create tag in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -69,25 +74,27 @@ func (h Handlers) PostTag(c echo.Context) error { } func (h Handlers) PutTag(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + tagID, err := uuid.Parse(c.Param("tagID")) if err != nil { - h.Logger.Info("could not parse query parameter `tagID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `tagID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if tagID == uuid.Nil { - h.Logger.Info("invalid tag ID", zap.Error(err)) + logger.Info("invalid tag ID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid tag ID")) } var req Tag if err := c.Bind(&req); err != nil { - h.Logger.Info("could not get tag from request", zap.Error(err)) + logger.Info("could not get tag from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() tag, err := h.Repository.UpdateTag(ctx, tagID, req.Name) if err != nil { - h.Logger.Error("failed to update tag in repository", zap.Error(err)) + logger.Error("failed to update tag in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -102,20 +109,22 @@ func (h Handlers) PutTag(c echo.Context) error { } func (h Handlers) DeleteTag(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + tagID, err := uuid.Parse(c.Param("tagID")) if err != nil { - h.Logger.Info("could not parse query parameter `tagID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `tagID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if tagID == uuid.Nil { - h.Logger.Info("invalid tag ID", zap.Error(err)) + logger.Info("invalid tag ID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, errors.New("invalid tag ID")) } - ctx := c.Request().Context() err = h.Repository.DeleteTag(ctx, tagID) if err != nil { - h.Logger.Error("failed to delete tag in repository", zap.Error(err)) + logger.Error("failed to delete tag in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } diff --git a/router/transaction.go b/router/transaction.go index 9e1def8b..c07fe5a3 100644 --- a/router/transaction.go +++ b/router/transaction.go @@ -9,6 +9,7 @@ import ( "github.com/google/uuid" "github.com/labstack/echo/v4" "github.com/samber/lo" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "github.com/traPtitech/Jomon/service" "go.uber.org/zap" @@ -46,6 +47,8 @@ type TransactionOverviewWithOneTarget struct { func (h Handlers) GetTransactions(c echo.Context) error { ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var sort *string if c.QueryParam("sort") != "" { s := c.QueryParam("sort") @@ -61,7 +64,7 @@ func (h Handlers) GetTransactions(c echo.Context) error { var err error s, err := service.StrToDate(c.QueryParam("since")) if err != nil { - h.Logger.Info("could not parse since as time.Time", zap.Error(err)) + logger.Info("could not parse since as time.Time", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } since = &s @@ -71,7 +74,7 @@ func (h Handlers) GetTransactions(c echo.Context) error { var err error u, err := service.StrToDate(c.QueryParam("until")) if err != nil { - h.Logger.Info("could not parse until as time.Time", zap.Error(err)) + logger.Info("could not parse until as time.Time", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } until = &u @@ -80,11 +83,11 @@ func (h Handlers) GetTransactions(c echo.Context) error { if limitQuery := c.QueryParam("limit"); limitQuery != "" { limitI, err := strconv.Atoi(limitQuery) if err != nil { - h.Logger.Info("could not parse limit as integer", zap.Error(err)) + logger.Info("could not parse limit as integer", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if limitI < 0 { - h.Logger.Info("received negative limit", zap.Int("limit", limitI)) + logger.Info("received negative limit", zap.Int("limit", limitI)) err := fmt.Errorf("negative limit(=%d) is invalid", limitI) return echo.NewHTTPError(http.StatusBadRequest, err) } @@ -94,11 +97,11 @@ func (h Handlers) GetTransactions(c echo.Context) error { if offsetQuery := c.QueryParam("offset"); offsetQuery != "" { offsetI, err := strconv.Atoi(offsetQuery) if err != nil { - h.Logger.Info("could not parse offset as integer", zap.Error(err)) + logger.Info("could not parse offset as integer", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } if offsetI < 0 { - h.Logger.Info("received negative offset", zap.Int("offset", offsetI)) + logger.Info("received negative offset", zap.Int("offset", offsetI)) err := fmt.Errorf("negative offset(=%d) is invalid", offsetI) return echo.NewHTTPError(http.StatusBadRequest, err) } @@ -119,7 +122,7 @@ func (h Handlers) GetTransactions(c echo.Context) error { var r uuid.UUID r, err := uuid.Parse(c.QueryParam("request")) if err != nil { - h.Logger.Info("could not parse request as uuid.UUID", zap.Error(err)) + logger.Info("could not parse request as uuid.UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } request = &r @@ -178,25 +181,27 @@ func (h Handlers) GetTransactions(c echo.Context) error { } func (h Handlers) PostTransaction(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var tx *TransactionOverview // TODO: validate if err := c.Bind(&tx); err != nil { - h.Logger.Info("could not get transaction overview from request", zap.Error(err)) + logger.Info("could not get transaction overview from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } transactions := []*Transaction{} - ctx := c.Request().Context() for _, target := range tx.Targets { if target == nil { - h.Logger.Info("target is nil") + logger.Info("target is nil") return echo.NewHTTPError(http.StatusBadRequest, "target is nil") } created, err := h.Repository.CreateTransaction( ctx, tx.Title, tx.Amount, *target, tx.Tags, tx.Group, tx.Request) if err != nil { - h.Logger.Error("failed to create transaction in repository", zap.Error(err)) + logger.Error("failed to create transaction in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -238,16 +243,18 @@ func (h Handlers) PostTransaction(c echo.Context) error { } func (h Handlers) GetTransaction(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + txID, err := uuid.Parse(c.Param("transactionID")) if err != nil { - h.Logger.Info("could not parse query parameter `transactionID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `transactionID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() tx, err := h.Repository.GetTransaction(ctx, txID) if err != nil { - h.Logger.Error("failed to get transaction from repository", zap.Error(err)) + logger.Error("failed to get transaction from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -287,27 +294,29 @@ func (h Handlers) GetTransaction(c echo.Context) error { } func (h Handlers) PutTransaction(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + txID, err := uuid.Parse(c.Param("transactionID")) if err != nil { - h.Logger.Info("could not parse query parameter `transactionID` as UUID", zap.Error(err)) + logger.Info("could not parse query parameter `transactionID` as UUID", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } var tx *TransactionOverviewWithOneTarget // TODO: validate if err := c.Bind(&tx); err != nil { - h.Logger.Info( + logger.Info( "could not get transaction overview with one target from request", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } - ctx := c.Request().Context() updated, err := h.Repository.UpdateTransaction( ctx, txID, tx.Title, tx.Amount, tx.Target, tx.Tags, tx.Group, tx.Request) if err != nil { - h.Logger.Error("failed to update transaction in repository", zap.Error(err)) + logger.Error("failed to update transaction in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } diff --git a/router/user.go b/router/user.go index f41965fd..316d73ef 100644 --- a/router/user.go +++ b/router/user.go @@ -9,6 +9,7 @@ import ( "github.com/labstack/echo/v4" "github.com/samber/lo" "github.com/traPtitech/Jomon/ent" + "github.com/traPtitech/Jomon/logging" "github.com/traPtitech/Jomon/model" "go.uber.org/zap" ) @@ -24,9 +25,12 @@ type User struct { } func (h Handlers) GetUsers(c echo.Context) error { - users, err := h.Repository.GetUsers(c.Request().Context()) + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + + users, err := h.Repository.GetUsers(ctx) if err != nil { - h.Logger.Error("failed to get users from repository", zap.Error(err)) + logger.Error("failed to get users from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -52,23 +56,25 @@ type PutUserRequest struct { } func (h Handlers) UpdateUserInfo(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + var newUser PutUserRequest if err := c.Bind(&newUser); err != nil { - h.Logger.Info("could not get user info from request", zap.Error(err)) + logger.Info("could not get user info from request", zap.Error(err)) return c.NoContent(http.StatusBadRequest) } - user, err := h.Repository.GetUserByName(c.Request().Context(), newUser.Name) + user, err := h.Repository.GetUserByName(ctx, newUser.Name) if err != nil { - h.Logger.Error("failed to get user from repository", zap.Error(err)) + logger.Error("failed to get user from repository", zap.Error(err)) return echo.NewHTTPError(http.StatusBadRequest, err) } updated, err := h.Repository.UpdateUser( - c.Request().Context(), - user.ID, newUser.Name, newUser.DisplayName, newUser.Admin) + ctx, user.ID, newUser.Name, newUser.DisplayName, newUser.Admin) if err != nil { - h.Logger.Error("failed to update user in repository", zap.Error(err)) + logger.Error("failed to update user in repository", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } @@ -93,24 +99,27 @@ func userFromModelUser(u model.User) User { } func (h Handlers) GetMe(c echo.Context) error { + ctx := c.Request().Context() + logger := logging.GetLogger(ctx) + sess, err := session.Get(h.SessionName, c) if err != nil { - h.Logger.Error("failed to get session", zap.Error(err)) + logger.Error("failed to get session", zap.Error(err)) return echo.NewHTTPError(http.StatusInternalServerError, err) } userInSession, ok := sess.Values[sessionUserKey].(User) if !ok { - h.Logger.Error("failed to parse stored session as user info") + logger.Error("failed to parse stored session as user info") return echo.NewHTTPError(http.StatusInternalServerError, "failed to get user info") } - modelUser, err := h.Repository.GetUserByID(c.Request().Context(), userInSession.ID) + modelUser, err := h.Repository.GetUserByID(ctx, userInSession.ID) if err != nil { if ent.IsNotFound(err) { - h.Logger.Error("failed to find user from DB by ID") + logger.Error("failed to find user from DB by ID") return c.JSON(http.StatusNotFound, err) } - h.Logger.Error("failed to get user by ID") + logger.Error("failed to get user by ID") return c.JSON(http.StatusInternalServerError, err) } user := userFromModelUser(*modelUser) diff --git a/testutil/context.go b/testutil/context.go index e70ae1b1..f4de539e 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -3,9 +3,13 @@ package testutil import ( "context" "testing" + + "github.com/traPtitech/Jomon/logging" ) func NewContext(t *testing.T) context.Context { t.Helper() - return context.Background() + logger := LoadLogger(t) + ctx := context.Background() + return logging.SetLogger(ctx, logger) } diff --git a/testutil/logger.go b/testutil/logger.go new file mode 100644 index 00000000..dd746539 --- /dev/null +++ b/testutil/logger.go @@ -0,0 +1,16 @@ +package testutil + +import ( + "testing" + + "github.com/stretchr/testify/require" + "github.com/traPtitech/Jomon/logging" + "go.uber.org/zap" +) + +func LoadLogger(t *testing.T) *zap.Logger { + t.Helper() + logger, err := logging.Load(logging.Development) + require.NoError(t, err) + return logger +}