Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(log)!: adopt slog (#7991)
zll600d4282c63d21f
diff --git a/backend/api/v1/actuator_service.go b/backend/api/v1/actuator_service.goindex 33da5c8e0c..9a28ea1c66 100644--- a/backend/api/v1/actuator_service.go+++ b/backend/api/v1/actuator_service.go@@ -2,9 +2,9 @@ package v1import ("context"+ "log/slog""time"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/types/known/emptypb"@@ -43,11 +43,11 @@ func (s *ActuatorService) GetActuatorInfo(ctx context.Context, _ *v1pb.GetActuatfunc (s *ActuatorService) UpdateActuatorInfo(ctx context.Context, request *v1pb.UpdateActuatorInfoRequest) (*v1pb.ActuatorInfo, error) {for _, path := range request.UpdateMask.Paths {if path == "debug" {- lvl := zap.InfoLevel+ lvl := slog.LevelInfoif request.Actuator.Debug {- lvl = zap.DebugLevel+ lvl = slog.LevelDebug}- log.SetLevel(lvl)+ log.GLogLevel.Set(lvl)}}@@ -110,7 +110,7 @@ func (s *ActuatorService) getServerInfo(ctx context.Context) (*v1pb.ActuatorInfoLastActiveTime: timestamppb.New(time.Unix(s.profile.LastActiveTs, 0)),WorkspaceId: workspaceID,GitopsWebhookUrl: setting.GitopsWebhookUrl,- Debug: log.EnabledLevel(zap.DebugLevel),+ Debug: slog.Default().Enabled(ctx, slog.LevelDebug),DevelopmentUseV2Scheduler: true,}diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.goindex 2dbb7513de..e3f35bf751 100644--- a/backend/api/v1/database_service.go+++ b/backend/api/v1/database_service.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""regexp""sort""strconv"@@ -17,7 +18,6 @@ import ("github.com/pingcap/tidb/parser/format""github.com/pkg/errors"openai "github.com/sashabaranov/go-openai"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/encoding/protojson"@@ -1726,7 +1726,7 @@ func (s *DatabaseService) createTransferProjectActivity(ctx context.Context, new)}if _, err := s.store.BatchCreateActivityV2(ctx, creates); err != nil {- log.Warn("failed to create activities for database project updates", zap.Error(err))+ slog.Warn("failed to create activities for database project updates", log.BBError(err))}return nil}@@ -1734,7 +1734,7 @@ func (s *DatabaseService) createTransferProjectActivity(ctx context.Context, newfunc getDefaultBackupSetting(instanceID, databaseName string) *v1pb.BackupSetting {sevenDays, err := convertPeriodTsToDuration(int(time.Duration(7 * 24 * time.Hour).Seconds()))if err != nil {- log.Warn("failed to convert period ts to duration", zap.Error(err))+ slog.Warn("failed to convert period ts to duration", log.BBError(err))}return &v1pb.BackupSetting{Name: fmt.Sprintf("%s%s/%s%s/%s", common.InstanceNamePrefix, instanceID, common.DatabaseIDPrefix, databaseName, common.BackupSettingSuffix),diff --git a/backend/api/v1/debug_interceptor.go b/backend/api/v1/debug_interceptor.goindex a9d960b0ed..facde2e06d 100644--- a/backend/api/v1/debug_interceptor.go+++ b/backend/api/v1/debug_interceptor.go@@ -2,10 +2,10 @@ package v1import ("context"+ "log/slog""runtime/debug""time"- "go.uber.org/zap""google.golang.org/grpc""google.golang.org/grpc/codes""google.golang.org/grpc/status"@@ -53,9 +53,9 @@ func (in *DebugInterceptor) DebugStreamInterceptor(request any, ss grpc.ServerStfunc (in *DebugInterceptor) debugInterceptorDo(ctx context.Context, request any, fullMethod string, err error) {st := status.Convert(err)if st.Code() == codes.Internal {- log.Error("Internal error intercepted", zap.String("method", fullMethod), zap.Error(err), zap.Any("request", request))+ slog.Error("Internal error intercepted", slog.String("method", fullMethod), log.BBError(err), slog.Any("request", request))}- if st.Code() == codes.Internal && log.EnabledLevel(zap.DebugLevel) {+ if st.Code() == codes.Internal && slog.Default().Enabled(ctx, slog.LevelDebug) {var role api.Roleif r, ok := ctx.Value(common.RoleContextKey).(api.Role); ok {role = rdiff --git a/backend/api/v1/inbox_service.go b/backend/api/v1/inbox_service.goindex 0ed0d924ab..25268b353e 100644--- a/backend/api/v1/inbox_service.go+++ b/backend/api/v1/inbox_service.go@@ -3,9 +3,9 @@ package v1import ("context""fmt"+ "log/slog""time"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status"@@ -104,7 +104,7 @@ func (s *InboxService) ListInbox(ctx context.Context, request *v1pb.ListInboxReqfor _, inbox := range inboxList {inboxV1, err := s.convertToInboxMessage(ctx, inbox)if err != nil {- log.Error("failed to convert inbox message", zap.Int("inbox", inbox.UID), zap.Error(err))+ slog.Error("failed to convert inbox message", slog.Int("inbox", inbox.UID), log.BBError(err))continue}resp.InboxMessages = append(resp.InboxMessages, inboxV1)diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.goindex a362a83926..060535ef02 100644--- a/backend/api/v1/instance_service.go+++ b/backend/api/v1/instance_service.go@@ -3,11 +3,11 @@ package v1import ("context""fmt"+ "log/slog""strings""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/types/known/emptypb"@@ -142,9 +142,9 @@ func (s *InstanceService) CreateInstance(ctx context.Context, request *v1pb.Creaif err == nil {defer driver.Close(ctx)if err := s.schemaSyncer.SyncInstance(ctx, instance); err != nil {- log.Warn("Failed to sync instance",- zap.String("instance", instance.ResourceID),- zap.Error(err))+ slog.Warn("Failed to sync instance",+ slog.String("instance", instance.ResourceID),+ log.BBError(err))}// Sync all databases in the instance asynchronously.s.stateCfg.InstanceDatabaseSyncChan <- instance@@ -234,9 +234,9 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, request *v1pb.Upda}if err := s.schemaSyncer.SyncInstance(ctx, instance); err != nil {- log.Warn("Failed to sync instance",- zap.String("instance", instance.ResourceID),- zap.Error(err))+ slog.Warn("Failed to sync instance",+ slog.String("instance", instance.ResourceID),+ log.BBError(err))}// Sync all databases in the instance asynchronously.s.stateCfg.InstanceDatabaseSyncChan <- instance@@ -277,7 +277,7 @@ func (s *InstanceService) syncSlowQueriesImpl(ctx context.Context, project *stor}defer driver.Close(ctx)if err := driver.CheckSlowQueryLogEnabled(ctx); err != nil {- log.Warn("slow query log is not enabled", zap.String("instance", instance.ResourceID), zap.Error(err))+ slog.Warn("slow query log is not enabled", slog.String("instance", instance.ResourceID), log.BBError(err))return nil}@@ -317,7 +317,7 @@ func (s *InstanceService) syncSlowQueriesImpl(ctx context.Context, project *stordefer driver.Close(ctx)return driver.CheckSlowQueryLogEnabled(ctx)}(); err != nil {- log.Warn("slow query log is not enabled", zap.String("database", database.DatabaseName), zap.Error(err))+ slog.Warn("slow query log is not enabled", slog.String("database", database.DatabaseName), log.BBError(err))continue}diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 4afe9fce02..a365f3a68a 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -4,13 +4,13 @@ import ("context""encoding/json""fmt"+ "log/slog""strconv""strings""time""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/encoding/protojson"@@ -640,7 +640,7 @@ func (s *IssueService) ApproveIssue(ctx context.Context, request *v1pb.ApproveIsLevel: api.ActivityInfo,Comment: fmt.Sprintf("Granted %s to %s (%s).", newUser.Name, newUser.Email, payload.GrantRequest.Role),}, &activity.Metadata{}); err != nil {- log.Warn("Failed to create project activity", zap.Error(err))+ slog.Warn("Failed to create project activity", log.BBError(err))}}@@ -677,7 +677,7 @@ func (s *IssueService) ApproveIssue(ctx context.Context, request *v1pb.ApproveIsreturn nil}(); err != nil {- log.Error("failed to create skipping steps activity after approving issue", zap.Error(err))+ slog.Error("failed to create skipping steps activity after approving issue", log.BBError(err))}if err := func() error {@@ -715,7 +715,7 @@ func (s *IssueService) ApproveIssue(ctx context.Context, request *v1pb.ApproveIsreturn nil}(); err != nil {- log.Error("failed to create approval step pending activity after creating issue", zap.Error(err))+ slog.Error("failed to create approval step pending activity after creating issue", log.BBError(err))}s.onIssueApproved(ctx, issue)@@ -823,7 +823,7 @@ func (s *IssueService) RejectIssue(ctx context.Context, request *v1pb.RejectIssu}return nil}(); err != nil {- log.Error("failed to create activity after rejecting issue", zap.Error(err))+ slog.Error("failed to create activity after rejecting issue", log.BBError(err))}issueV1, err := convertToIssue(ctx, s.store, issue)@@ -933,7 +933,7 @@ func (s *IssueService) RequestIssue(ctx context.Context, request *v1pb.RequestIsreturn nil}(); err != nil {- log.Error("failed to create skipping steps activity after approving issue", zap.Error(err))+ slog.Error("failed to create skipping steps activity after approving issue", log.BBError(err))}issueV1, err := convertToIssue(ctx, s.store, issue)@@ -1125,7 +1125,7 @@ func (s *IssueService) BatchUpdateIssuesStatus(ctx context.Context, request *v1p}return errs}(); err != nil {- log.Error("failed to create activity after changing the issue status", zap.Error(err))+ slog.Error("failed to create activity after changing the issue status", log.BBError(err))}return &v1pb.BatchUpdateIssuesStatusResponse{}, nil@@ -1237,7 +1237,7 @@ func (s *IssueService) onIssueApproved(ctx context.Context, issue *store.IssueMe}return nil}(); err != nil {- log.Debug("failed to update issue status to done if grant request issue is approved", zap.Error(err))+ slog.Debug("failed to update issue status to done if grant request issue is approved", log.BBError(err))}}}diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.goindex d15953aa96..928cf4aee7 100644--- a/backend/api/v1/org_policy_service.go+++ b/backend/api/v1/org_policy_service.go@@ -3,11 +3,11 @@ package v1import ("context""fmt"+ "log/slog""strings""github.com/google/cel-go/cel""github.com/pkg/errors"- "go.uber.org/zap"expr "google.golang.org/genproto/googleapis/type/expr""google.golang.org/grpc/codes""google.golang.org/grpc/status"@@ -92,7 +92,7 @@ func (s *OrgPolicyService) ListPolicies(ctx context.Context, request *v1pb.ListPif err != nil {st := status.Convert(err)if st.Code() == codes.NotFound {- log.Debug("failed to found resource for policy", zap.Error(err), zap.String("resource_type", string(policy.ResourceType)), zap.Int("resource_id", policy.ResourceUID))+ slog.Debug("failed to found resource for policy", log.BBError(err), slog.String("resource_type", string(policy.ResourceType)), slog.Int("resource_id", policy.ResourceUID))continue}return nil, errdiff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex 4f8b8517d4..20cbd17800 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "log/slog""path""reflect""strconv"@@ -13,7 +14,6 @@ import ("github.com/google/cel-go/cel""github.com/gosimple/slug""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/types/known/emptypb"@@ -92,7 +92,7 @@ func (s *ProjectService) CreateProject(ctx context.Context, request *v1pb.Createsetting, err := s.store.GetDataClassificationSetting(ctx)if err != nil {- log.Error("failed to find classification setting", zap.Error(err))+ slog.Error("failed to find classification setting", log.BBError(err))}if setting != nil && len(setting.Configs) != 0 {projectMessage.DataClassificationConfigID = setting.Configs[0].Id@@ -640,7 +640,7 @@ func (s *ProjectService) UnsetProjectGitOpsInfo(ctx context.Context, request *v1repo.ExternalWebhookID,); err != nil {// Despite the error here, we have deleted the repository in the database, we still return success.- log.Error("failed to delete webhook for project", zap.String("project", projectName), zap.Int("repo", repo.UID), zap.Error(err))+ slog.Error("failed to delete webhook for project", slog.String("project", projectName), slog.Int("repo", repo.UID), log.BBError(err))}}@@ -675,7 +675,7 @@ func (s *ProjectService) CreateIAMPolicyUpdateActivity(ctx context.Context, remofor _, a := range activities {if _, err := s.activityManager.CreateActivity(ctx, a, &activity.Metadata{}); err != nil {- log.Warn("Failed to create project activity", zap.Error(err))+ slog.Warn("Failed to create project activity", log.BBError(err))}}}@@ -1237,7 +1237,7 @@ func (s *ProjectService) setupVCSSQLReviewBranch(ctx context.Context, repositoryif err != nil {return nil, err}- log.Debug("VCS target branch info", zap.String("last_commit", branch.LastCommitID), zap.String("name", branch.Name))+ slog.Debug("VCS target branch info", slog.String("last_commit", branch.LastCommitID), slog.String("name", branch.Name))branchCreate := &vcsPlugin.BranchInfo{Name: fmt.Sprintf("bytebase-vcs-%d", time.Now().Unix()),@@ -1302,12 +1302,12 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitHub(},)if err != nil {- log.Debug(+ slog.Debug("Failed to get file meta",- zap.String("file", github.SQLReviewActionFilePath),- zap.String("last_commit", branch.LastCommitID),- zap.Int("code", common.ErrorCode(err).Int()),- zap.Error(err),+ slog.String("file", github.SQLReviewActionFilePath),+ slog.String("last_commit", branch.LastCommitID),+ slog.Int("code", common.ErrorCode(err).Int()),+ log.BBError(err),)} else if fileMeta != nil {fileLastCommitID = fileMeta.LastCommitID@@ -1438,12 +1438,12 @@ func (s *ProjectService) setupVCSSQLReviewCIForAzureDevOps(},)if err != nil {- log.Debug(+ slog.Debug("Failed to get file meta",- zap.String("file", azure.SQLReviewPipelineFilePath),- zap.String("last_commit", branch.LastCommitID),- zap.Int("code", common.ErrorCode(err).Int()),- zap.Error(err),+ slog.String("file", azure.SQLReviewPipelineFilePath),+ slog.String("last_commit", branch.LastCommitID),+ slog.Int("code", common.ErrorCode(err).Int()),+ log.BBError(err),)} else if fileMeta != nil {fileLastCommitID = fileMeta.LastCommitID@@ -1509,11 +1509,11 @@ func (s *ProjectService) createOrUpdateVCSSQLReviewFileForGitLab(},)if err != nil {- log.Debug(+ slog.Debug("Failed to get file meta",- zap.String("last_commit", branch.LastCommitID),- zap.Int("code", common.ErrorCode(err).Int()),- zap.Error(err),+ slog.String("last_commit", branch.LastCommitID),+ slog.Int("code", common.ErrorCode(err).Int()),+ log.BBError(err),)if common.ErrorCode(err) == common.NotFound {fileExisted = falsediff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.goindex e7d70f334a..9a111834e3 100644--- a/backend/api/v1/rollout_service.go+++ b/backend/api/v1/rollout_service.go@@ -4,13 +4,13 @@ import ("context""encoding/json""fmt"+ "log/slog""sort""strconv""time""github.com/google/go-cmp/cmp""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/encoding/protojson"@@ -518,7 +518,7 @@ func (s *RolloutService) BatchRunTasks(ctx context.Context, request *v1pb.BatchR}if err := s.activityManager.BatchCreateActivitiesForRunTasks(ctx, tasksToRun, issue, request.Reason, user.ID); err != nil {- log.Error("failed to batch create activities for running tasks", zap.Error(err))+ slog.Error("failed to batch create activities for running tasks", log.BBError(err))}return &v1pb.BatchRunTasksResponse{}, nil@@ -590,7 +590,7 @@ func (s *RolloutService) BatchSkipTasks(ctx context.Context, request *v1pb.Batch}if err := s.activityManager.BatchCreateActivitiesForSkipTasks(ctx, tasksToSkip, issue, request.Reason, updaterID); err != nil {- log.Error("failed to batch create activities for skipping tasks", zap.Error(err))+ slog.Error("failed to batch create activities for skipping tasks", log.BBError(err))}return &v1pb.BatchSkipTasksResponse{}, nil@@ -715,7 +715,7 @@ func (s *RolloutService) BatchCancelTaskRuns(ctx context.Context, request *v1pb.}if err := s.activityManager.BatchCreateActivitiesForCancelTaskRuns(ctx, tasks, issue, request.Reason, principalID); err != nil {- log.Error("failed to batch create activities for cancel task runs", zap.Error(err))+ slog.Error("failed to batch create activities for cancel task runs", log.BBError(err))}return &v1pb.BatchCancelTaskRunsResponse{}, nil@@ -949,7 +949,7 @@ func (s *RolloutService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlas.stateCfg.ApprovalFinding.Store(issue.UID, issue)return nil}(); err != nil {- log.Error("failed to update issue to refind approval", zap.Error(err))+ slog.Error("failed to update issue to refind approval", log.BBError(err))}}diff --git a/backend/api/v1/rollout_service_task.go b/backend/api/v1/rollout_service_task.goindex e85b1e25c7..767167d1fd 100644--- a/backend/api/v1/rollout_service_task.go+++ b/backend/api/v1/rollout_service_task.go@@ -4,11 +4,11 @@ import ("context""encoding/json""fmt"+ "log/slog""strconv""strings""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -117,7 +117,7 @@ func getTaskCreatesFromCreateDatabaseConfig(ctx context.Context, s *store.Store,// And also, meet an error in here is not a big deal, we will just use the original DatabaseName.driver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, nil /* database */)if err != nil {- log.Warn("failed to get admin database driver for instance %q, please check the connection for admin data source", zap.Error(err), zap.String("instance", instance.Title))+ slog.Warn("failed to get admin database driver for instance %q, please check the connection for admin data source", log.BBError(err), slog.String("instance", instance.Title))break}defer driver.Close(ctx)@@ -125,7 +125,7 @@ func getTaskCreatesFromCreateDatabaseConfig(ctx context.Context, s *store.Store,var unused anydb := driver.GetDB()if err := db.QueryRowContext(ctx, "SHOW VARIABLES LIKE 'lower_case_table_names'").Scan(&unused, &lowerCaseTableNames); err != nil {- log.Warn("failed to get lower_case_table_names for instance %q", zap.Error(err), zap.String("instance", instance.Title))+ slog.Warn("failed to get lower_case_table_names for instance %q", log.BBError(err), slog.String("instance", instance.Title))break}if lowerCaseTableNames == 1 {diff --git a/backend/api/v1/sheet_service.go b/backend/api/v1/sheet_service.goindex 6bb81fbbf8..6795f94ef1 100644--- a/backend/api/v1/sheet_service.go+++ b/backend/api/v1/sheet_service.go@@ -3,6 +3,7 @@ package v1import ("context""fmt"+ "log/slog""path/filepath""regexp""strconv"@@ -10,7 +11,6 @@ import ("time""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/types/known/emptypb"@@ -277,14 +277,14 @@ func (s *SheetService) SearchSheets(ctx context.Context, request *v1pb.SearchShereturn nil, status.Errorf(codes.Internal, fmt.Sprintf("failed to check access with error: %v", err))}if !canAccess {- log.Warn("cannot access sheet", zap.String("name", sheet.Name))+ slog.Warn("cannot access sheet", slog.String("name", sheet.Name))continue}v1pbSheet, err := s.convertToAPISheetMessage(ctx, sheet)if err != nil {st := status.Convert(err)if st.Code() == codes.NotFound {- log.Debug("failed to found resource for sheet", zap.Error(err), zap.Int("id", sheet.UID), zap.Int("project", sheet.ProjectUID))+ slog.Debug("failed to found resource for sheet", log.BBError(err), slog.Int("id", sheet.UID), slog.Int("project", sheet.ProjectUID))continue}return nil, errdiff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 43df49a9f3..cf4ad70963 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -9,6 +9,7 @@ import ("encoding/json""fmt""io"+ "log/slog""reflect""strconv""strings"@@ -20,7 +21,6 @@ import (tidbast "github.com/pingcap/tidb/parser/ast""github.com/pkg/errors""github.com/xuri/excelize/v2"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/proto"@@ -120,7 +120,7 @@ func (s *SQLService) AdminExecute(server v1pb.SQLService_AdminExecuteServer) errdefer func() {if conn != nil {if err := conn.Close(); err != nil {- log.Warn("failed to close connection", zap.Error(err))+ slog.Warn("failed to close connection", log.BBError(err))}}if driver != nil {@@ -161,7 +161,7 @@ func (s *SQLService) AdminExecute(server v1pb.SQLService_AdminExecuteServer) errsanitizeResults(result)if err := s.postAdminExecute(ctx, activity, durationNs, queryErr); err != nil {- log.Error("failed to post admin execute activity", zap.Error(err))+ slog.Error("failed to post admin execute activity", log.BBError(err))}response := &v1pb.AdminExecuteResponse{}@@ -206,11 +206,11 @@ func (s *SQLService) postAdminExecute(ctx context.Context, activity *store.Activ// TODO: update the advice listpayloadBytes, err := json.Marshal(payload)if err != nil {- log.Warn("Failed to marshal activity after executing sql statement",- zap.String("database_name", payload.DatabaseName),- zap.Int("instance_id", payload.InstanceID),- zap.String("statement", payload.Statement),- zap.Error(err))+ slog.Warn("Failed to marshal activity after executing sql statement",+ slog.String("database_name", payload.DatabaseName),+ slog.Int("instance_id", payload.InstanceID),+ slog.String("statement", payload.Statement),+ log.BBError(err))return status.Errorf(codes.Internal, "Failed to marshal activity after executing sql statement: %v", err)}@@ -310,11 +310,11 @@ func (s *SQLService) postExport(ctx context.Context, activity *store.ActivityMespayloadBytes, err := json.Marshal(payload)if err != nil {- log.Warn("Failed to marshal activity after exporting sql statement",- zap.String("database_name", payload.DatabaseName),- zap.Int("instance_id", payload.InstanceID),- zap.String("statement", payload.Statement),- zap.Error(err))+ slog.Warn("Failed to marshal activity after exporting sql statement",+ slog.String("database_name", payload.DatabaseName),+ slog.Int("instance_id", payload.InstanceID),+ slog.String("statement", payload.Statement),+ log.BBError(err))return status.Errorf(codes.Internal, "Failed to marshal activity after exporting sql statement: %v", err)}@@ -895,11 +895,11 @@ func (s *SQLService) createExportActivity(ctx context.Context, user *store.UserM// TODO: use v1 activity API instead ofactivityBytes, err := json.Marshal(payload)if err != nil {- log.Warn("Failed to marshal activity before exporting sql statement",- zap.String("database_name", payload.DatabaseName),- zap.Int("instance_id", payload.InstanceID),- zap.String("statement", payload.Statement),- zap.Error(err))+ slog.Warn("Failed to marshal activity before exporting sql statement",+ slog.String("database_name", payload.DatabaseName),+ slog.Int("instance_id", payload.InstanceID),+ slog.String("statement", payload.Statement),+ log.BBError(err))return nil, status.Errorf(codes.Internal, "Failed to construct activity payload: %v", err)}@@ -1034,11 +1034,11 @@ func (s *SQLService) postQuery(ctx context.Context, _ *v1pb.QueryRequest, advicepayloadBytes, err := json.Marshal(payload)if err != nil {- log.Warn("Failed to marshal activity after executing sql statement",- zap.String("database_name", payload.DatabaseName),- zap.Int("instance_id", payload.InstanceID),- zap.String("statement", payload.Statement),- zap.Error(err))+ slog.Warn("Failed to marshal activity after executing sql statement",+ slog.String("database_name", payload.DatabaseName),+ slog.Int("instance_id", payload.InstanceID),+ slog.String("statement", payload.Statement),+ log.BBError(err))return nil, status.Errorf(codes.Internal, "Failed to marshal activity after executing sql statement: %v", err)}@@ -1278,7 +1278,7 @@ func allPostgresSystemObjects(statement string) bool {// We need to distinguish between specified public schema and by default.resources, err := parser.ExtractResourceList(parser.Postgres, "", "", statement)if err != nil {- log.Debug("Failed to extract resource list from statement", zap.String("statement", statement), zap.Error(err))+ slog.Debug("Failed to extract resource list from statement", slog.String("statement", statement), log.BBError(err))return false}systemSchemas := make(map[string]bool)@@ -1307,11 +1307,11 @@ func (s *SQLService) createQueryActivity(ctx context.Context, user *store.UserMe// TODO: use v1 activity API instead ofactivityBytes, err := json.Marshal(payload)if err != nil {- log.Warn("Failed to marshal activity before executing sql statement",- zap.String("database_name", payload.DatabaseName),- zap.Int("instance_id", payload.InstanceID),- zap.String("statement", payload.Statement),- zap.Error(err))+ slog.Warn("Failed to marshal activity before executing sql statement",+ slog.String("database_name", payload.DatabaseName),+ slog.Int("instance_id", payload.InstanceID),+ slog.String("statement", payload.Statement),+ log.BBError(err))return nil, status.Errorf(codes.Internal, "Failed to construct activity payload: %v", err)}@@ -1411,13 +1411,13 @@ func (s *SQLService) getSensitiveSchemaInfo(ctx context.Context, instance *store// Build the filtered maskingExceptionPolicy for current principal.var maskingExceptionContainsCurrentPrincipal []*storepb.MaskingExceptionPolicy_MaskingExceptionif maskingExceptionPolicy != nil {- log.Debug("found masking exception policy for project", zap.String("database", databaseName), zap.String("project", database.ProjectID), zap.Any("masking exception policy", maskingExceptionPolicy))+ slog.Debug("found masking exception policy for project", slog.String("database", databaseName), slog.String("project", database.ProjectID), slog.Any("masking exception policy", maskingExceptionPolicy))for _, maskingException := range maskingExceptionPolicy.MaskingExceptions {if maskingException.Action != action {continue}if maskingException.Member == currentPrincipal.Email {- log.Debug("hit masking exception for current principal", zap.String("database", databaseName), zap.String("project", database.ProjectID), zap.Any("masking exception", maskingException))+ slog.Debug("hit masking exception for current principal", slog.String("database", databaseName), slog.String("project", database.ProjectID), slog.Any("masking exception", maskingException))maskingExceptionContainsCurrentPrincipal = append(maskingExceptionContainsCurrentPrincipal, maskingException)break}@@ -1430,7 +1430,7 @@ func (s *SQLService) getSensitiveSchemaInfo(ctx context.Context, instance *storefor _, dataClassificationSetting := range classificationSetting.Configs {if dataClassificationSetting.Id == project.DataClassificationConfigID {dataClassificationConfig = dataClassificationSetting- log.Debug("found data classification config for project", zap.String("project", project.ResourceID), zap.Any("data classification config id", dataClassificationConfig.Id))+ slog.Debug("found data classification config for project", slog.String("project", project.ResourceID), slog.Any("data classification config id", dataClassificationConfig.Id))break}}@@ -1451,7 +1451,7 @@ func (s *SQLService) getSensitiveSchemaInfo(ctx context.Context, instance *store}] = maskData}}- log.Debug("found masking policy for database", zap.String("database", databaseName), zap.Any("masking policy", maskingPolicy))+ slog.Debug("found masking policy for database", slog.String("database", databaseName), slog.Any("masking policy", maskingPolicy))columnMap := make(sensitiveDataMap)for _, data := range maskingPolicy.MaskData {@@ -1482,7 +1482,7 @@ func (s *SQLService) getSensitiveSchemaInfo(ctx context.Context, instance *storeColumnList: []db.ColumnInfo{},}for _, column := range table.Columns {- log.Debug("processing sensitive schema info", zap.String("schema", schema.Name), zap.String("table", table.Name))+ slog.Debug("processing sensitive schema info", slog.String("schema", schema.Name), slog.String("table", table.Name))maskingLevel, err := evaluateMaskingLevelOfColumn(database, schema.Name, table.Name, column, maskingPolicyMap, maskingRulePolicy, maskingExceptionContainsCurrentPrincipal, dataClassificationConfig)if err != nil {return nil, errors.Wrapf(err, "failed to evaluate masking level of database %q, schema %q, table %q, column %q", databaseName, schema.Name, table.Name, column.Name)@@ -1519,7 +1519,7 @@ func (s *SQLService) getSensitiveSchemaInfo(ctx context.Context, instance *storeColumnList: []db.ColumnInfo{},}for _, column := range table.Columns {- log.Debug("processing sensitive schema info", zap.String("database", database.DatabaseName), zap.String("schema", schema.Name), zap.String("table", table.Name), zap.String("column", column.Name))+ slog.Debug("processing sensitive schema info", slog.String("database", database.DatabaseName), slog.String("schema", schema.Name), slog.String("table", table.Name), slog.String("column", column.Name))maskingLevel, err := evaluateMaskingLevelOfColumn(database, schema.Name, table.Name, column, maskingPolicyMap, maskingRulePolicy, maskingExceptionContainsCurrentPrincipal, dataClassificationConfig)if err != nil {return nil, errors.Wrapf(err, "failed to evaluate masking level of database %q, schema %q, table %q, column %q", databaseName, schema.Name, table.Name, column.Name)@@ -1582,7 +1582,7 @@ func evaluateMaskingLevelOfColumn(databaseMessage *store.DatabaseMessage, schema}maskingData, ok := maskingPolicyMap[key]if (!ok) || (maskingData.MaskingLevel == storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED) {- log.Debug("column set DEFAULT masking level in masking policy or masking policy not set yet", zap.String("column", column.Name), zap.Any("masking policy", maskingData))+ slog.Debug("column set DEFAULT masking level in masking policy or masking policy not set yet", slog.String("column", column.Name), slog.Any("masking policy", maskingData))// If the column has DEFAULT masking level in maskingPolicy or not set yet,// we will eval the maskingRulePolicy to get the maskingLevel.columnClassificationLevel := getClassificationLevelOfColumn(column.Classification, dataClassificationConfig)@@ -1602,19 +1602,19 @@ func evaluateMaskingLevelOfColumn(databaseMessage *store.DatabaseMessage, schema}if pass {finalLevel = maskingRule.MaskingLevel- log.Debug("hit masking rule", zap.String("column", column.Name), zap.Any("masking rule", maskingRule), zap.Any("masking level", maskingRule.MaskingLevel.String()))+ slog.Debug("hit masking rule", slog.String("column", column.Name), slog.Any("masking rule", maskingRule), slog.Any("masking level", maskingRule.MaskingLevel.String()))break}}} else {- log.Debug("column set specific masking level in masking policy", zap.String("column", column.Name), zap.Any("masking level", maskingData.MaskingLevel.String()))+ slog.Debug("column set specific masking level in masking policy", slog.String("column", column.Name), slog.Any("masking level", maskingData.MaskingLevel.String()))finalLevel = maskingData.MaskingLevel}if finalLevel == storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED || finalLevel == storepb.MaskingLevel_NONE {// After looking up the maskingPolicy and maskingRulePolicy, if the maskingLevel is still MASKING_LEVEL_UNSPECIFIED or NONE,// return the MASKING_LEVEL_NONE, which means no masking and do not need eval exceptions anymore.- log.Debug("After looking up maskingPolicy and maskingRulePolicy, the masking level is UNSPECIFIED or NONE", zap.Any("masking level", finalLevel.String()))+ slog.Debug("After looking up maskingPolicy and maskingRulePolicy, the masking level is UNSPECIFIED or NONE", slog.Any("masking level", finalLevel.String()))return storepb.MaskingLevel_NONE, nil}@@ -1641,14 +1641,14 @@ func evaluateMaskingLevelOfColumn(databaseMessage *store.DatabaseMessage, schemaif !hit {continue}- log.Debug("hit masking exception", zap.String("column", column.Name), zap.Any("masking exception", filteredMaskingException), zap.Any("masking level", filteredMaskingException.MaskingLevel.String()))+ slog.Debug("hit masking exception", slog.String("column", column.Name), slog.Any("masking exception", filteredMaskingException), slog.Any("masking level", filteredMaskingException.MaskingLevel.String()))// TODO(zp): Expectedly, a column should hit only one exception,// but we can take the strictest level here to make the whole program more robust.if cmp.Less[storepb.MaskingLevel](filteredMaskingException.MaskingLevel, finalLevel) {finalLevel = filteredMaskingException.MaskingLevel}}- log.Debug("final level of column", zap.String("column", column.Name), zap.Any("final level", finalLevel.String()))+ slog.Debug("final level of column", slog.String("column", column.Name), slog.Any("final level", finalLevel.String()))return finalLevel, nil}func getClassificationLevelOfColumn(columnClassificationID string, classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig) string {@@ -2470,7 +2470,7 @@ func hasDatabaseAccessRights(principalID int, projectPolicy *store.IAMPolicyMess}ok, err := evaluateQueryExportPolicyCondition(binding.Condition.Expression, attributes)if err != nil {- log.Error("failed to evaluate condition", zap.Error(err), zap.String("condition", binding.Condition.Expression))+ slog.Error("failed to evaluate condition", log.BBError(err), slog.String("condition", binding.Condition.Expression))break}if ok {diff --git a/backend/bin/bb/cmd/root.go b/backend/bin/bb/cmd/root.goindex 5b2f87817f..d9f6d79bb2 100644--- a/backend/bin/bb/cmd/root.go+++ b/backend/bin/bb/cmd/root.go@@ -3,8 +3,6 @@ package cmdimport ("github.com/spf13/cobra"-- "github.com/bytebase/bytebase/backend/common/log")// NewRootCmd creates the root command.@@ -24,6 +22,5 @@ func NewRootCmd() *cobra.Command {// Execute is the execute command for root command.func Execute() (err error) {- defer log.Sync()return NewRootCmd().Execute()}diff --git a/backend/bin/server/cmd/root.go b/backend/bin/server/cmd/root.goindex cbf003dc5b..4175a091bf 100644--- a/backend/bin/server/cmd/root.go+++ b/backend/bin/server/cmd/root.go@@ -4,6 +4,7 @@ package cmdimport ("context""fmt"+ "log/slog""net""net/http""os"@@ -14,7 +15,6 @@ import ("github.com/pkg/errors""github.com/spf13/cobra"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -186,26 +186,25 @@ func checkPort(port int) error {func start() {if flags.debug {- log.SetLevel(zap.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)}- defer log.Sync()var err errorif flags.externalURL != "" {flags.externalURL, err = common.NormalizeExternalURL(flags.externalURL)if err != nil {- log.Error("invalid --external-url", zap.Error(err))+ slog.Error("invalid --external-url", log.BBError(err))return}}if err := checkDataDir(); err != nil {- log.Error(err.Error())+ slog.Error(err.Error())return}if err := checkCloudBackupFlags(); err != nil {- log.Error("invalid flags for cloud backup", zap.Error(err))+ slog.Error("invalid flags for cloud backup", log.BBError(err))return}@@ -220,17 +219,17 @@ func start() {// and then complain unable to bind port. Thus we cannot rely on checking /healthz. As a// workaround, we check whether the port is available here.if err := checkPort(flags.port); err != nil {- log.Error(fmt.Sprintf("server port %d is not available", flags.port), zap.Error(err))+ slog.Error(fmt.Sprintf("server port %d is not available", flags.port), log.BBError(err))return}if profile.UseEmbedDB() {if err := checkPort(profile.DatastorePort); err != nil {- log.Error(fmt.Sprintf("database port %d is not available", profile.DatastorePort), zap.Error(err))+ slog.Error(fmt.Sprintf("database port %d is not available", profile.DatastorePort), log.BBError(err))return}}if err := checkPort(profile.GrpcPort); err != nil {- log.Error(fmt.Sprintf("gRPC server port %d is not available", profile.GrpcPort), zap.Error(err))+ slog.Error(fmt.Sprintf("gRPC server port %d is not available", profile.GrpcPort), log.BBError(err))return}@@ -244,7 +243,7 @@ func start() {signal.Notify(c, os.Interrupt, syscall.SIGTERM)go func() {sig := <-c- log.Info(fmt.Sprintf("%s received.", sig.String()))+ slog.Info(fmt.Sprintf("%s received.", sig.String()))if s != nil {_ = s.Shutdown(ctx)}@@ -253,7 +252,7 @@ func start() {s, err = server.NewServer(ctx, profile)if err != nil {- log.Error("Cannot new server", zap.Error(err))+ slog.Error("Cannot new server", log.BBError(err))return}@@ -266,7 +265,7 @@ func start() {// Execute program.if err := s.Run(ctx, flags.port); err != nil {if err != http.ErrServerClosed {- log.Error(err.Error())+ slog.Error(err.Error())_ = s.Shutdown(ctx)cancel()}diff --git a/backend/bin/sql-service/cmd/root.go b/backend/bin/sql-service/cmd/root.goindex 627e26cd2a..f4d00750b5 100644--- a/backend/bin/sql-service/cmd/root.go+++ b/backend/bin/sql-service/cmd/root.go@@ -4,13 +4,13 @@ package cmdimport ("context""fmt"+ "log/slog""net/http""os""os/signal""syscall""github.com/spf13/cobra"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -103,13 +103,12 @@ func init() {func start() {if flags.debug {- log.SetLevel(zap.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)}- defer log.Sync()// check flagsif !common.HasPrefixes(flags.host, "http://", "https://") {- log.Error(fmt.Sprintf("--host %s must start with http:// or https://", flags.host))+ slog.Error(fmt.Sprintf("--host %s must start with http:// or https://", flags.host))return}@@ -125,7 +124,7 @@ func start() {signal.Notify(c, os.Interrupt, syscall.SIGTERM)go func() {sig := <-c- log.Info(fmt.Sprintf("%s received.", sig.String()))+ slog.Info(fmt.Sprintf("%s received.", sig.String()))if s != nil {_ = s.Shutdown(ctx)}@@ -134,14 +133,14 @@ func start() {s, err := server.NewServer(ctx, activeProfile)if err != nil {- log.Error("Cannot new server", zap.Error(err))+ slog.Error("Cannot new server", log.BBError(err))return}fmt.Printf(greetingBanner, fmt.Sprintf("Version %s has started at %s:%d", activeProfile.Version, activeProfile.BackendHost, activeProfile.BackendPort))// Execute program.if err := s.Run(); err != nil {if err != http.ErrServerClosed {- log.Error(err.Error())+ slog.Error(err.Error())_ = s.Shutdown(ctx)cancel()}diff --git a/backend/common/log/logger.go b/backend/common/log/logger.godeleted file mode 100644index 26762a5df5..0000000000--- a/backend/common/log/logger.go+++ /dev/null@@ -1,67 +0,0 @@-// Package log implements a simple logging package.-package log--import (- "go.uber.org/zap"- "go.uber.org/zap/zapcore"-)--var (- // `gl` is the global logger.- // Other packages should use public methods such as Info/Error to do the logging.- // For other types of logging, e.g. logging to a separate file, they should use their own loggers.- gl *zap.Logger- gLevel zap.AtomicLevel-)--// Initializes the global console logger.-func init() {- gLevel = zap.NewAtomicLevelAt(zap.InfoLevel)- gl, _ = zap.Config{- Level: gLevel,- Development: true,- // Use "console" to print readable stacktrace.- Encoding: "console",- EncoderConfig: zap.NewDevelopmentEncoderConfig(),- OutputPaths: []string{"stderr"},- ErrorOutputPaths: []string{"stderr"},- }.Build(- // Skip one caller stack to locate the correct caller.- zap.AddCallerSkip(1),- )-}--// SetLevel wraps the zap Level's SetLevel method.-func SetLevel(level zapcore.Level) {- gLevel.SetLevel(level)-}--// EnabledLevel wraps the zap Level's Enabled method.-func EnabledLevel(level zapcore.Level) bool {- return gLevel.Enabled(level)-}--// Debug wraps the zap Logger's Debug method.-func Debug(msg string, fields ...zap.Field) {- gl.Debug(msg, fields...)-}--// Info wraps the zap Logger's Info method.-func Info(msg string, fields ...zap.Field) {- gl.Info(msg, fields...)-}--// Warn wraps the zap Logger's Warn method.-func Warn(msg string, fields ...zap.Field) {- gl.Warn(msg, fields...)-}--// Error wraps the zap Logger's Error method.-func Error(msg string, fields ...zap.Field) {- gl.Error(msg, fields...)-}--// Sync wraps the zap Logger's Sync method.-func Sync() {- _ = gl.Sync()-}diff --git a/backend/common/log/slog_utils.go b/backend/common/log/slog_utils.gonew file mode 100644index 0000000000..5fbfe775f7--- /dev/null+++ b/backend/common/log/slog_utils.go@@ -0,0 +1,49 @@+package log++import (+ "log/slog"+ "os"+ "runtime/debug"+ "strings"+)++var GLogLevel *slog.LevelVar++// Initializes the slog configuration.+func init() {+ GLogLevel = new(slog.LevelVar)++ // https://sourcegraph.com/github.com/uber-go/zap/-/blob/zapcore/entry.go?L117+ replace := func(groups []string, a slog.Attr) slog.Attr {+ if a.Key == slog.SourceKey {+ if source, ok := a.Value.Any().(*slog.Source); ok {+ idx := strings.LastIndexByte(source.File, '/')+ if idx == -1 {+ return a+ }+ // Find the penultimate separator.+ idx = strings.LastIndexByte(source.File[:idx], '/')+ if idx == -1 {+ return a+ }+ source.File = source.File[idx+1:]+ }+ }+ return a+ }++ textHandler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{AddSource: true, Level: GLogLevel, ReplaceAttr: replace})+ slog.SetDefault(slog.New(textHandler))+}++func BBError(err error) slog.Attr {+ return slog.String("error", err.Error())+}++func BBStack(key string) slog.Attr {+ return slog.Any(key, debug.Stack())+}++func BBStrings(key string, ss []string) slog.Attr {+ return slog.Any(key, ss)+}diff --git a/backend/component/activity/manager.go b/backend/component/activity/manager.goindex 1707adf383..4fd75a88ce 100644--- a/backend/component/activity/manager.go+++ b/backend/component/activity/manager.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""sort""strconv""strings"@@ -22,7 +23,6 @@ import (storepb "github.com/bytebase/bytebase/proto/generated-go/store""github.com/pkg/errors"- "go.uber.org/zap")// Manager is the activity manager.@@ -421,9 +421,9 @@ func (m *Manager) CreateActivity(ctx context.Context, create *store.ActivityMesswebhookCtx, err := m.getWebhookContext(ctx, activity, meta, updater)if err != nil {- log.Warn("Failed to get webhook context",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to get webhook context",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return activity, nil}// Call external webhook endpoint in Go routine to avoid blocking web serving thread.@@ -442,12 +442,12 @@ func postWebhookList(ctx context.Context, webhookCtx *webhook.Context, webhookLireturn webhook.Post(hook.Type, *webhookCtx)}); err != nil {// The external webhook endpoint might be invalid which is out of our code control, so we just emit a warning- log.Warn("Failed to post webhook event on activity",- zap.String("webhook type", hook.Type),- zap.String("webhook name", hook.Title),- zap.String("activity type", webhookCtx.ActivityType),- zap.String("title", webhookCtx.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event on activity",+ slog.String("webhook type", hook.Type),+ slog.String("webhook name", hook.Title),+ slog.String("activity type", webhookCtx.ActivityType),+ slog.String("title", webhookCtx.Title),+ log.BBError(err))return}}(&webhookCtx, hook)@@ -486,9 +486,9 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitcase api.ActivityIssueFieldUpdate:update := new(api.ActivityIssueFieldUpdatePayload)if err := json.Unmarshal([]byte(activity.Payload), update); err != nil {- log.Warn("Failed to post webhook event after changing the issue field, failed to unmarshal payload",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue field, failed to unmarshal payload",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return nil, err}switch update.FieldID {@@ -498,26 +498,26 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitif update.OldValue != "" {oldID, err := strconv.Atoi(update.OldValue)if err != nil {- log.Warn("Failed to post webhook event after changing the issue assignee, old assignee id is not number",- zap.String("issue_name", meta.Issue.Title),- zap.String("old_assignee_id", update.OldValue),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue assignee, old assignee id is not number",+ slog.String("issue_name", meta.Issue.Title),+ slog.String("old_assignee_id", update.OldValue),+ log.BBError(err))return nil, err}oldAssignee, err = m.store.GetUserByID(ctx, oldID)if err != nil {- log.Warn("Failed to post webhook event after changing the issue assignee, failed to find old assignee",- zap.String("issue_name", meta.Issue.Title),- zap.String("old_assignee_id", update.OldValue),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue assignee, failed to find old assignee",+ slog.String("issue_name", meta.Issue.Title),+ slog.String("old_assignee_id", update.OldValue),+ log.BBError(err))return nil, err}if oldAssignee == nil {err := errors.Errorf("failed to post webhook event after changing the issue assignee, old assignee not found for ID %v", oldID)- log.Warn(err.Error(),- zap.String("issue_name", meta.Issue.Title),- zap.String("old_assignee_id", update.OldValue),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.String("issue_name", meta.Issue.Title),+ slog.String("old_assignee_id", update.OldValue),+ log.BBError(err))return nil, err}}@@ -525,18 +525,18 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitif update.NewValue != "" {newID, err := strconv.Atoi(update.NewValue)if err != nil {- log.Warn("Failed to post webhook event after changing the issue assignee, new assignee id is not number",- zap.String("issue_name", meta.Issue.Title),- zap.String("new_assignee_id", update.NewValue),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue assignee, new assignee id is not number",+ slog.String("issue_name", meta.Issue.Title),+ slog.String("new_assignee_id", update.NewValue),+ log.BBError(err))return nil, err}newAssignee, err = m.store.GetUserByID(ctx, newID)if err != nil {- log.Warn("Failed to post webhook event after changing the issue assignee, failed to find new assignee",- zap.String("issue_name", meta.Issue.Title),- zap.String("new_assignee_id", update.NewValue),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue assignee, failed to find new assignee",+ slog.String("issue_name", meta.Issue.Title),+ slog.String("new_assignee_id", update.NewValue),+ log.BBError(err))return nil, err}@@ -559,10 +559,10 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitcase api.ActivityPipelineStageStatusUpdate:payload := &api.ActivityPipelineStageStatusUpdatePayload{}if err := json.Unmarshal([]byte(activity.Payload), payload); err != nil {- log.Warn(+ slog.Warn("failed to post webhook event after stage status updating, failed to unmarshal payload",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return nil, err}link += fmt.Sprintf("?stage=%d", payload.StageID)@@ -576,26 +576,26 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitcase api.ActivityPipelineTaskStatusUpdate:update := &api.ActivityPipelineTaskStatusUpdatePayload{}if err := json.Unmarshal([]byte(activity.Payload), update); err != nil {- log.Warn("Failed to post webhook event after changing the issue task status, failed to unmarshal payload",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue task status, failed to unmarshal payload",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return nil, err}task, err := m.store.GetTaskByID(ctx, update.TaskID)if err != nil {- log.Warn("Failed to post webhook event after changing the issue task status, failed to find task",- zap.String("issue_name", meta.Issue.Title),- zap.Int("task_id", update.TaskID),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue task status, failed to find task",+ slog.String("issue_name", meta.Issue.Title),+ slog.Int("task_id", update.TaskID),+ log.BBError(err))return nil, err}if task == nil {err := errors.Errorf("failed to post webhook event after changing the issue task status, task not found for ID %v", update.TaskID)- log.Warn(err.Error(),- zap.String("issue_name", meta.Issue.Title),- zap.Int("task_id", update.TaskID),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.String("issue_name", meta.Issue.Title),+ slog.Int("task_id", update.TaskID),+ log.BBError(err))return nil, err}@@ -622,7 +622,7 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitskipped, skippedReason, err := getTaskSkippedAndReason(task)if err != nil {err := errors.Wrap(err, "failed to get skipped and skippedReason from the task")- log.Warn(err.Error(), zap.String("task.Payload", task.Payload), zap.Error(err))+ slog.Warn(err.Error(), slog.String("task.Payload", task.Payload), log.BBError(err))return nil, err}if skipped {@@ -636,9 +636,9 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitif len(task.TaskRunList) == 0 {err := errors.Errorf("expect at least 1 TaskRun, get 0")- log.Warn(err.Error(),- zap.Any("task", task),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.Any("task", task),+ log.BBError(err))return nil, err}@@ -650,9 +650,9 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitvar result api.TaskRunResultPayloadif err := json.Unmarshal([]byte(task.TaskRunList[0].Result), &result); err != nil {err := errors.Wrap(err, "failed to unmarshal TaskRun Result")- log.Warn(err.Error(),- zap.Any("TaskRun", task.TaskRunList[0]),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.Any("TaskRun", task.TaskRunList[0]),+ log.BBError(err))return nil, err}webhookTaskResult.Detail = result.Detail@@ -661,26 +661,26 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitcase api.ActivityPipelineTaskRunStatusUpdate:payload := &api.ActivityPipelineTaskRunStatusUpdatePayload{}if err := json.Unmarshal([]byte(activity.Payload), payload); err != nil {- log.Warn("Failed to post webhook event after changing the issue task run status, failed to unmarshal payload",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue task run status, failed to unmarshal payload",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return nil, err}task, err := m.store.GetTaskByID(ctx, payload.TaskID)if err != nil {- log.Warn("Failed to post webhook event after changing the issue task status, failed to find task",- zap.String("issue_name", meta.Issue.Title),- zap.Int("task_id", payload.TaskID),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue task status, failed to find task",+ slog.String("issue_name", meta.Issue.Title),+ slog.Int("task_id", payload.TaskID),+ log.BBError(err))return nil, err}if task == nil {err := errors.Errorf("failed to post webhook event after changing the issue task status, task not found for ID %v", payload.TaskID)- log.Warn(err.Error(),- zap.String("issue_name", meta.Issue.Title),- zap.Int("task_id", payload.TaskID),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.String("issue_name", meta.Issue.Title),+ slog.Int("task_id", payload.TaskID),+ log.BBError(err))return nil, err}@@ -703,9 +703,9 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitif len(task.TaskRunList) == 0 {err := errors.Errorf("expect at least 1 TaskRun, get 0")- log.Warn(err.Error(),- zap.Any("task", task),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.Any("task", task),+ log.BBError(err))return nil, err}@@ -717,9 +717,9 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitvar result api.TaskRunResultPayloadif err := json.Unmarshal([]byte(task.TaskRunList[0].Result), &result); err != nil {err := errors.Wrap(err, "failed to unmarshal TaskRun Result")- log.Warn(err.Error(),- zap.Any("TaskRun", task.TaskRunList[0]),- zap.Error(err))+ slog.Warn(err.Error(),+ slog.Any("TaskRun", task.TaskRunList[0]),+ log.BBError(err))return nil, err}webhookTaskResult.Detail = result.Detail@@ -731,7 +731,7 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activit_, skippedReason, err := getTaskSkippedAndReason(task)if err != nil {err := errors.Wrap(err, "failed to get skipped and skippedReason from the task")- log.Warn(err.Error(), zap.String("task.Payload", task.Payload), zap.Error(err))+ slog.Warn(err.Error(), slog.String("task.Payload", task.Payload), log.BBError(err))return nil, err}webhookTaskResult.SkippedReason = skippedReason@@ -742,21 +742,21 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitcase api.ActivityIssueApprovalNotify:payload := &api.ActivityIssueApprovalNotifyPayload{}if err := json.Unmarshal([]byte(activity.Payload), payload); err != nil {- log.Warn("Failed to post webhook event after changing the issue approval node status, failed to unmarshal payload",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue approval node status, failed to unmarshal payload",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return nil, err}protoPayload := &storepb.ActivityIssueApprovalNotifyPayload{}if err := protojson.Unmarshal([]byte(payload.ProtoPayload), protoPayload); err != nil {- log.Warn("Failed to post webhook event")+ slog.Warn("Failed to post webhook event")}pendingStep := protoPayload.ApprovalSteptitle = "Issue approval needed - " + meta.Issue.Titleif len(pendingStep.Nodes) != 1 {- log.Warn("Failed to post webhook event after changing the issue approval node status, pending step nodes length is not 1")+ slog.Warn("Failed to post webhook event after changing the issue approval node status, pending step nodes length is not 1")return nil, errors.Errorf("pending step nodes length is not 1, got %v", len(pendingStep.Nodes))}@@ -793,17 +793,17 @@ func (m *Manager) getWebhookContext(ctx context.Context, activity *store.Activitusers, err := usersGetter(ctx)if err != nil {- log.Warn("Failed to post webhook event after changing the issue approval node status, failed to get users",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue approval node status, failed to get users",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))return nil, err}for _, user := range users {phoneNumber, err := phonenumbers.Parse(user.Phone, "")if err != nil {- log.Warn("Failed to post webhook event after changing the issue approval node status, failed to parse phone number",- zap.String("issue_name", meta.Issue.Title),- zap.Error(err))+ slog.Warn("Failed to post webhook event after changing the issue approval node status, failed to parse phone number",+ slog.String("issue_name", meta.Issue.Title),+ log.BBError(err))continue}phone := strconv.FormatInt(int64(*phoneNumber.NationalNumber), 10)diff --git a/backend/enterprise/service/license.go b/backend/enterprise/service/license.goindex f7c442c022..beea75d816 100644--- a/backend/enterprise/service/license.go+++ b/backend/enterprise/service/license.go@@ -4,12 +4,12 @@ package serviceimport ("context""encoding/json"+ "log/slog""math""time""github.com/golang-jwt/jwt/v4""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -209,26 +209,26 @@ func (s *LicenseService) fetchLicense(ctx context.Context) (*enterpriseAPI.Licenfunc (s *LicenseService) loadLicense(ctx context.Context) *enterpriseAPI.License {license, err := s.findEnterpriseLicense(ctx)if err != nil {- log.Debug("failed to load enterprise license", zap.Error(err))+ slog.Debug("failed to load enterprise license", log.BBError(err))}if license == nil {license, err = s.findTrialingLicense(ctx)if err != nil {- log.Debug("failed to load trialing license", zap.Error(err))+ slog.Debug("failed to load trialing license", log.BBError(err))}}if license == nil {license, err = s.fetchLicense(ctx)if err != nil {- log.Debug("failed to fetch license", zap.Error(err))+ slog.Debug("failed to fetch license", log.BBError(err))}}if license == nil {return nil}if err := license.Valid(); err != nil {- log.Debug("license is invalid", zap.Error(err))+ slog.Debug("license is invalid", log.BBError(err))return nil}@@ -259,11 +259,11 @@ func (s *LicenseService) findEnterpriseLicense(ctx context.Context) (*enterprisereturn nil, errors.Wrapf(err, "failed to parse enterprise license")}if license != nil {- log.Debug(+ slog.Debug("Load valid license",- zap.String("plan", license.Plan.String()),- zap.Time("expiresAt", time.Unix(license.ExpiresTs, 0)),- zap.Int("instanceCount", license.InstanceCount),+ slog.String("plan", license.Plan.String()),+ slog.Time("expiresAt", time.Unix(license.ExpiresTs, 0)),+ slog.Int("instanceCount", license.InstanceCount),)return license, nil}diff --git a/backend/enterprise/service/provider.go b/backend/enterprise/service/provider.goindex 7b51bd114b..c2a88b3139 100644--- a/backend/enterprise/service/provider.go+++ b/backend/enterprise/service/provider.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""time"@@ -13,7 +14,6 @@ import ("google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/enterprise/config"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store"@@ -61,7 +61,7 @@ func NewLicenseProvider(config *config.Config, store *store.Store) *LicenseProvifunc (p *LicenseProvider) FetchLicense(ctx context.Context) (string, error) {nextFetchTime := p.lastFetchTime + int64(fetchLicenseInterval.Seconds())if time.Now().Unix() < nextFetchTime {- log.Debug(fmt.Sprintf("skip fetching license until %d", nextFetchTime))+ slog.Debug(fmt.Sprintf("skip fetching license until %d", nextFetchTime))return "", nil}diff --git a/backend/metric/collector/instance_count.go b/backend/metric/collector/instance_count.goindex 394b5b83c3..2be2d092e0 100644--- a/backend/metric/collector/instance_count.go+++ b/backend/metric/collector/instance_count.go@@ -2,10 +2,8 @@ package collectorimport ("context"+ "log/slog"- "go.uber.org/zap"-- "github.com/bytebase/bytebase/backend/common/log"metricAPI "github.com/bytebase/bytebase/backend/metric""github.com/bytebase/bytebase/backend/plugin/metric""github.com/bytebase/bytebase/backend/store"@@ -39,7 +37,7 @@ func (c *instanceCountCollector) Collect(ctx context.Context) ([]*metric.Metric,UID: &instanceCountMetric.EnvironmentID,})if err != nil {- log.Debug("failed to get environment by id", zap.Int("id", instanceCountMetric.EnvironmentID))+ slog.Debug("failed to get environment by id", slog.Int("id", instanceCountMetric.EnvironmentID))continue}diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.goindex 9f3feea37d..a7e7a1eac6 100644--- a/backend/migrator/migrator.go+++ b/backend/migrator/migrator.go@@ -7,6 +7,7 @@ import ("embed""fmt""io/fs"+ "log/slog""path/filepath""sort""strconv"@@ -14,10 +15,8 @@ import ("github.com/blang/semver/v4""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log"api "github.com/bytebase/bytebase/backend/legacyapi"dbdriver "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"@@ -58,7 +57,7 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, strictUseDb bool, pgBif err != nil {return nil, errors.Wrapf(err, "failed to get cutoff version")}- log.Info(fmt.Sprintf("The prod cutoff schema version: %s", cutoffSchemaVersion))+ slog.Info(fmt.Sprintf("The prod cutoff schema version: %s", cutoffSchemaVersion))if err := initializeSchema(ctx, storeInstance, metadataDriver, cutoffSchemaVersion, serverVersion); err != nil {return nil, err}@@ -93,7 +92,7 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, strictUseDb bool, pgBif err != nil {return nil, errors.Wrap(err, "failed to get current schema version")}- log.Info(fmt.Sprintf("Current schema version after migration: %s", verAfter))+ slog.Info(fmt.Sprintf("Current schema version after migration: %s", verAfter))if err := setupDemoData(demoName, metadataDriver.GetDB()); err != nil {return nil, errors.Wrapf(err, "failed to setup demo data."+@@ -116,7 +115,7 @@ func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataDif exists {return nil}- log.Info("The database schema has not been setup.")+ slog.Info("The database schema has not been setup.")latestSchemaPath := fmt.Sprintf("migration/%s/%s", common.ReleaseModeProd, latestSchemaFile)buf, err := migrationFS.ReadFile(latestSchemaPath)@@ -160,7 +159,7 @@ func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataD}); err != nil {return err}- log.Info(fmt.Sprintf("Completed database initial migration with version %s.", cutoffSchemaVersion))+ slog.Info(fmt.Sprintf("Completed database initial migration with version %s.", cutoffSchemaVersion))return nil}@@ -191,11 +190,11 @@ func getLatestVersion(ctx context.Context, storeInstance *store.Store) (semver.V// Non-success migration history record is an anomaly, in the case where the actual// migration has been applied, the followup migration will likely fail because the// schema has already been applied. Thus emitting a warning here will assist debugging.- log.Warn(fmt.Sprintf("Found %s migration history", h.Status),- zap.String("type", string(h.Type)),- zap.String("version", h.Version),- zap.String("description", h.Description),- zap.String("statement", stmt),+ slog.Warn(fmt.Sprintf("Found %s migration history", h.Status),+ slog.String("type", string(h.Type)),+ slog.String("version", h.Version),+ slog.String("description", h.Description),+ slog.String("statement", stmt),)continue}@@ -216,11 +215,11 @@ func getLatestVersion(ctx context.Context, storeInstance *store.Store) (semver.V// setupDemoData loads the demo data.func setupDemoData(demoName string, db *sql.DB) error {if demoName == "" {- log.Debug("Skip setting up demo data. Demo not specified.")+ slog.Debug("Skip setting up demo data. Demo not specified.")return nil}- log.Info(fmt.Sprintf("Setting up demo %q...", demoName))+ slog.Info(fmt.Sprintf("Setting up demo %q...", demoName))// Reset existing demo data.if err := applyDataFile("demo/reset.sql", db); err != nil {@@ -244,13 +243,13 @@ func setupDemoData(demoName string, db *sql.DB) error {return errors.Wrapf(err, "Failed to load demo data: %q", name)}}- log.Info("Completed demo data setup.")+ slog.Info("Completed demo data setup.")return nil}// applyDataFile runs a single demo data file within a transaction.func applyDataFile(name string, db *sql.DB) error {- log.Info(fmt.Sprintf("Applying data file %s...", name))+ slog.Info(fmt.Sprintf("Applying data file %s...", name))tx, err := db.Begin()if err != nil {return err@@ -282,8 +281,8 @@ const (//// The procedure follows https://github.com/bytebase/bytebase/blob/main/docs/schema-update-guide.md.func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdriver.Driver, cutoffSchemaVersion, curVer semver.Version, mode common.ReleaseMode, serverVersion, databaseName string) error {- log.Info("Apply database migration if needed...")- log.Info(fmt.Sprintf("Current schema version before migration: %s", curVer))+ slog.Info("Apply database migration if needed...")+ slog.Info(fmt.Sprintf("Current schema version before migration: %s", curVer))var histories []*store.InstanceChangeHistoryMessage// Because dev migrations don't use semantic versioning, we have to look at all migration history to@@ -313,7 +312,7 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbd}for _, minorVersion := range minorVersions {- log.Info(fmt.Sprintf("Starting minor version migration cycle from %s ...", minorVersion))+ slog.Info(fmt.Sprintf("Starting minor version migration cycle from %s ...", minorVersion))names, err := fs.Glob(migrationFS, fmt.Sprintf("migration/%s/%d.%d/*.sql", common.ReleaseModeProd, minorVersion.Major, minorVersion.Minor))if err != nil {return err@@ -334,10 +333,10 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbd// after - prod 1.3 with 123.sql; dev: something else.// When dev starts, it will try to apply version 1.3 including 123.sql. If we don't skip, the same statement will be re-applied and most likely to fail.if mode == common.ReleaseModeDev && migrationExists(string(buf), histories) {- log.Info(fmt.Sprintf("Skip migrating migration file %s that's already migrated.", pv.filename))+ slog.Info(fmt.Sprintf("Skip migrating migration file %s that's already migrated.", pv.filename))continue}- log.Info(fmt.Sprintf("Migrating %s...", pv.version))+ slog.Info(fmt.Sprintf("Migrating %s...", pv.version))mi := &dbdriver.MigrationInfo{InstanceID: nil,CreatorID: api.SystemBotID,@@ -359,9 +358,9 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdretVersion = pv.version}if retVersion.EQ(curVer) {- log.Info(fmt.Sprintf("Database schema is at version %s; nothing to migrate.", curVer))+ slog.Info(fmt.Sprintf("Database schema is at version %s; nothing to migrate.", curVer))} else {- log.Info(fmt.Sprintf("Completed database migration from version %s to %s.", curVer, retVersion))+ slog.Info(fmt.Sprintf("Completed database migration from version %s to %s.", curVer, retVersion))}}@@ -414,18 +413,18 @@ func migrateDev(ctx context.Context, storeInstance *store.Store, metadataDriver// Skip migrations that are already applied, otherwise the migration reattempt will most likely to fail with already exists error.for _, m := range devMigrations {if migrationExists(m.statement, histories) {- log.Info(fmt.Sprintf("Skip migrating dev migration file %s that's already migrated.", m.filename))+ slog.Info(fmt.Sprintf("Skip migrating dev migration file %s that's already migrated.", m.filename))} else {migrations = append(migrations, m)}}if len(migrations) == 0 {- log.Info("Skip dev mode migration; no new version.")+ slog.Info("Skip dev mode migration; no new version.")return nil}for _, m := range migrations {- log.Info(fmt.Sprintf("Migrating dev %s...", m.filename))+ slog.Info(fmt.Sprintf("Migrating dev %s...", m.filename))// We expect to use semantic versioning for dev environment too because getLatestVersion() always expect to get the latest version in semantic format.mi := &dbdriver.MigrationInfo{InstanceID: nil,@@ -555,7 +554,7 @@ func getMinorMigrationVersions(names []string, currentVersion semver.Version) ([// If the migration version is less than to the current version, we will skip the migration since it's already applied.// We should still double check the current version in case there's any patch needed.if version.LT(currentVersion) {- log.Debug(fmt.Sprintf("Skip migration %s; the current schema version %s is higher.", version, currentVersion))+ slog.Debug(fmt.Sprintf("Skip migration %s; the current schema version %s is higher.", version, currentVersion))continue}migrateVersions = append(migrateVersions, version)diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex 98c52a0e0a..18083eb6e6 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -3,12 +3,12 @@ package migratorimport ("context""fmt"+ "log/slog""path""testing""github.com/blang/semver/v4""github.com/stretchr/testify/require"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -146,7 +146,7 @@ var ()func TestMigrationCompatibility(t *testing.T) {- log.SetLevel(zap.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)pgDir := t.TempDir()pgBinDir, err := postgres.Install(path.Join(pgDir, "resource"))pgDataDir := path.Join(pgDir, "data")diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 750da84007..99ff89aeb7 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -5,11 +5,13 @@ package advisorimport ("context""database/sql"+ "encoding/json""fmt"+ "log/slog"+ "strings""sync""github.com/pkg/errors"- "go.uber.org/zap/zapcore""github.com/bytebase/bytebase/backend/plugin/advisor/catalog""github.com/bytebase/bytebase/backend/plugin/advisor/db"@@ -491,28 +493,21 @@ type Advice struct {Details string `json:"details,omitempty"`}-// MarshalLogObject constructs a field that carries Advice.-func (a Advice) MarshalLogObject(enc zapcore.ObjectEncoder) error {- enc.AddString("status", string(a.Status))- enc.AddInt("code", int(a.Code))- enc.AddString("title", a.Title)- enc.AddString("content", a.Content)- enc.AddInt("line", a.Line)- enc.AddString("details", a.Details)- return nil-}--// ZapAdviceArray is a helper to format zap.Array.-type ZapAdviceArray []Advice--// MarshalLogArray implements the zapcore.ArrayMarshaler interface.-func (array ZapAdviceArray) MarshalLogArray(enc zapcore.ArrayEncoder) error {- for i := range array {- if err := enc.AppendObject(array[i]); err != nil {- return err+// SLogAdviceArray is a helper to format array of Advice.+type SLogAdviceArray []Advice++// LogValue implements the LogValuer interface.+func (arr SLogAdviceArray) LogValue() slog.Value {+ logArr := []string{}+ for _, advice := range arr {+ payload, err := json.Marshal(advice)+ if err != nil {+ logArr = append(logArr, err.Error())+ continue}+ logArr = append(logArr, string(payload))}- return nil+ return slog.StringValue(strings.Join(logArr, ","))}// SyntaxMode is the type of syntax mode.diff --git a/backend/plugin/advisor/mssql/advisor_column_maximum_varchar_length.go b/backend/plugin/advisor/mssql/advisor_column_maximum_varchar_length.goindex 4393bc273d..cd2a8789a7 100644--- a/backend/plugin/advisor/mssql/advisor_column_maximum_varchar_length.go+++ b/backend/plugin/advisor/mssql/advisor_column_maximum_varchar_length.go@@ -3,13 +3,13 @@ package mssqlimport ("fmt"+ "log/slog""math""strconv""github.com/antlr4-go/antlr/v4"parser "github.com/bytebase/tsql-parser""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/advisor"@@ -103,7 +103,7 @@ func (l *columnMaximumVarcharLengthChecker) EnterData_type(ctx *parser.Data_type}length, err := strconv.Atoi(ctx.GetScale().GetText())if err != nil {- log.Error("failed to convert scale to int", zap.Error(err))+ slog.Error("failed to convert scale to int", log.BBError(err))}currentLength = lengthline = ctx.GetScale().GetLine()diff --git a/backend/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.go b/backend/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.goindex b5e1a1244f..6f748887a0 100644--- a/backend/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.go+++ b/backend/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.go@@ -4,12 +4,10 @@ package pgimport ("fmt"-- "go.uber.org/zap"+ "log/slog""github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/advisor""github.com/bytebase/bytebase/backend/plugin/advisor/db"parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"@@ -98,9 +96,9 @@ func (checker *indexPrimaryKeyTypeAllowlistChecker) Visit(in ast.Node) ast.Visitif !allowType(checker.allowlist, column.Type) {typeText, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, column.Type)if err != nil {- log.Warn("Failed to deparse the PostgreSQL data type",- zap.String("columnName", column.ColumnName),- zap.String("originalSQL", in.Text()))+ slog.Warn("Failed to deparse the PostgreSQL data type",+ slog.String("columnName", column.ColumnName),+ slog.String("originalSQL", in.Text()))typeText = ""}checker.adviceList = append(checker.adviceList, advisor.Advice{diff --git a/backend/plugin/advisor/snowflake/advisor_naming_table.go b/backend/plugin/advisor/snowflake/advisor_naming_table.goindex b9c5fabebb..672b21d296 100644--- a/backend/plugin/advisor/snowflake/advisor_naming_table.go+++ b/backend/plugin/advisor/snowflake/advisor_naming_table.go@@ -3,15 +3,14 @@ package snowflakeimport ("fmt"+ "log/slog""regexp""strings""github.com/antlr4-go/antlr/v4"parser "github.com/bytebase/snowsql-parser""github.com/pkg/errors"- "go.uber.org/zap"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/advisor""github.com/bytebase/bytebase/backend/plugin/advisor/db")@@ -113,7 +112,7 @@ func (l *namingTableListener) EnterAlter_table(ctx *parser.Alter_tableContext) {allObjectNames := ctx.AllObject_name()if len(allObjectNames) != 2 {- log.Warn("Unexpected number of object names in alter table rename statement", zap.Int("objectNameCount", len(allObjectNames)))+ slog.Warn("Unexpected number of object names in alter table rename statement", slog.Int("objectNameCount", len(allObjectNames)))return}diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 8dfddcf4a3..0fd359467d 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -6,12 +6,12 @@ import ("database/sql""encoding/json""fmt"+ "log/slog""regexp""sort""strings""github.com/pkg/errors"- "go.uber.org/zap"tidbparser "github.com/pingcap/tidb/parser"tidbast "github.com/pingcap/tidb/parser/ast"@@ -751,7 +751,7 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext SadvisorType, err := getAdvisorTypeByRule(rule.Type, checkContext.DbType)if err != nil {if rule.Engine != "" {- log.Warn("not supported rule", zap.String("rule type", string(rule.Type)), zap.String("engine", string(rule.Engine)), zap.Error(err))+ slog.Warn("not supported rule", slog.String("rule type", string(rule.Type)), slog.String("engine", string(rule.Engine)), log.BBError(err))}continue}@@ -949,7 +949,7 @@ func convertWalkThroughErrorToAdvice(checkContext SQLReviewCheckContext, err errreturn nil, errors.Errorf("invalid payload for ColumnIsReferencedByView, expect []string but found %T", walkThroughError.Payload)}if definition, err := getViewDefinition(checkContext, list); err != nil {- log.Warn("failed to get view definition", zap.Error(err))+ slog.Warn("failed to get view definition", log.BBError(err))} else {details = definition}@@ -971,7 +971,7 @@ func convertWalkThroughErrorToAdvice(checkContext SQLReviewCheckContext, err errreturn nil, errors.Errorf("invalid payload for TableIsReferencedByView, expect []string but found %T", walkThroughError.Payload)}if definition, err := getViewDefinition(checkContext, list); err != nil {- log.Warn("failed to get view definition", zap.Error(err))+ slog.Warn("failed to get view definition", log.BBError(err))} else {details = definition}diff --git a/backend/plugin/app/feishu/feishu.go b/backend/plugin/app/feishu/feishu.goindex f421f7d3bf..beb3f10072 100644--- a/backend/plugin/app/feishu/feishu.go+++ b/backend/plugin/app/feishu/feishu.go@@ -8,13 +8,13 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""strings""sync/atomic""time""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -388,7 +388,7 @@ func retry(ctx context.Context, client *http.Client, token *string, tokenRefreshreturn 0, nil, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)}if err := resp.Body.Close(); err != nil {- log.Warn("failed to close resp body", zap.Error(err))+ slog.Warn("failed to close resp body", log.BBError(err))}var response struct {diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.goindex 375f293d68..dd9ed5f66f 100644--- a/backend/plugin/db/clickhouse/clickhouse.go+++ b/backend/plugin/db/clickhouse/clickhouse.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""math/big""reflect""strings"@@ -16,7 +17,6 @@ import ("github.com/paulmach/orb/encoding/wkt""github.com/pkg/errors""github.com/shopspring/decimal"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/structpb"@@ -79,10 +79,10 @@ func (driver *Driver) Open(_ context.Context, dbType db.Type, config db.ConnectiDialTimeout: 10 * time.Second,})- log.Debug("Opening ClickHouse driver",- zap.String("addr", addr),- zap.String("environment", connCtx.EnvironmentID),- zap.String("database", connCtx.InstanceID),+ slog.Debug("Opening ClickHouse driver",+ slog.String("addr", addr),+ slog.String("environment", connCtx.EnvironmentID),+ slog.String("database", connCtx.InstanceID),)driver.dbType = dbType@@ -143,7 +143,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, _ drowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/dm/dm.go b/backend/plugin/db/dm/dm.goindex a5b952620d..7e4674e373 100644--- a/backend/plugin/db/dm/dm.go+++ b/backend/plugin/db/dm/dm.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""strconv""strings""time"@@ -12,7 +13,6 @@ import (// Import go-dm DM driver._ "gitee.com/chunanyong/dm""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""github.com/bytebase/bytebase/backend/common/log"@@ -106,7 +106,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, optrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/mongodb/mongodb.go b/backend/plugin/db/mongodb/mongodb.goindex a865423f00..c07a5f3038 100644--- a/backend/plugin/db/mongodb/mongodb.go+++ b/backend/plugin/db/mongodb/mongodb.go@@ -8,6 +8,7 @@ import ("encoding/json""fmt""io"+ "log/slog""net/url""os""os/exec"@@ -17,7 +18,6 @@ import ("github.com/pkg/errors""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""github.com/bytebase/bytebase/backend/common/log"@@ -209,7 +209,7 @@ func (driver *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement stri// We make best-effort attempt to parse the content and fallback to single bulk result on failure.result, err := getSimpleStatementResult(outContent.Bytes())if err != nil {- log.Error("failed to get simple statement result", zap.String("content", outContent.String()), zap.Error(err))+ slog.Error("failed to get simple statement result", slog.String("content", outContent.String()), log.BBError(err))} else {result.Latency = durationpb.New(time.Since(startTime))result.Statement = statementdiff --git a/backend/plugin/db/mongodb/role.go b/backend/plugin/db/mongodb/role.goindex abfd979c46..8648102951 100644--- a/backend/plugin/db/mongodb/role.go+++ b/backend/plugin/db/mongodb/role.go@@ -3,11 +3,11 @@ package mongodbimport ("context""encoding/json"+ "log/slog""github.com/pkg/errors""go.mongodb.org/mongo-driver/bson"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -55,7 +55,7 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instancevar commandResult UsersInfoif err := database.RunCommand(ctx, command).Decode(&commandResult); err != nil {if isAtlasUnauthorizedError(err) {- log.Info("Skip getting user list because the user is not authorized to run the command 'usersInfo' in atlas cluster M0/M2/M5")+ slog.Info("Skip getting user list because the user is not authorized to run the command 'usersInfo' in atlas cluster M0/M2/M5")return nil, nil}return nil, errors.Wrap(err, "cannot run usersInfo command")diff --git a/backend/plugin/db/mongodb/sync.go b/backend/plugin/db/mongodb/sync.goindex 5fa6964feb..ab07c538b8 100644--- a/backend/plugin/db/mongodb/sync.go+++ b/backend/plugin/db/mongodb/sync.go@@ -3,17 +3,16 @@ package mongodbimport ("context""encoding/json"+ "log/slog""sort""strings""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo"- "go.uber.org/zap""github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -125,7 +124,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchema}dataSize64, err := convertEmptyInterfaceToInt64(dataSize)if err != nil {- log.Debug("Failed to convert dataSize to int64", zap.Any("dataSize", dataSize))+ slog.Debug("Failed to convert dataSize to int64", slog.Any("dataSize", dataSize))}totalIndexSize, ok := commandResult["totalIndexSize"]@@ -134,7 +133,7 @@ func (driver *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchema}totalIndexSize64, err := convertEmptyInterfaceToInt64(totalIndexSize)if err != nil {- log.Debug("Failed to convert totalIndexSize to int64", zap.Any("totalIndexSize", totalIndexSize))+ slog.Debug("Failed to convert totalIndexSize to int64", slog.Any("totalIndexSize", totalIndexSize))}// Get collection indexes.diff --git a/backend/plugin/db/mssql/mssql.go b/backend/plugin/db/mssql/mssql.goindex 7e1682203f..caa0c5c1ee 100644--- a/backend/plugin/db/mssql/mssql.go+++ b/backend/plugin/db/mssql/mssql.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""net/url""strings""time"@@ -14,8 +15,6 @@ import (_ "github.com/microsoft/go-mssqldb/integratedauth/krb5""google.golang.org/protobuf/types/known/durationpb"- "go.uber.org/zap"-"github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"@@ -106,7 +105,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/mysql/dump.go b/backend/plugin/db/mysql/dump.goindex 47c1782989..fb521f99e4 100644--- a/backend/plugin/db/mysql/dump.go+++ b/backend/plugin/db/mysql/dump.go@@ -7,13 +7,12 @@ import ("encoding/json""fmt""io"+ "log/slog""os/exec""regexp""strings""time"- "go.uber.org/zap"-"github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -100,10 +99,10 @@ func (driver *Driver) Dump(ctx context.Context, out io.Writer, schemaOnly bool)// Before we dump the real data, we should record the binlog position for PITR.// Please refer to https://github.com/bytebase/bytebase/blob/main/docs/design/pitr-mysql.md#full-backup for details.if !schemaOnly {- log.Debug("flush tables in database with read locks",- zap.String("database", driver.databaseName))+ slog.Debug("flush tables in database with read locks",+ slog.String("database", driver.databaseName))if err := FlushTablesWithReadLock(ctx, driver.dbType, conn, driver.databaseName); err != nil {- log.Error("flush tables failed", zap.Error(err))+ slog.Error("flush tables failed", log.BBError(err))return "", err}@@ -111,9 +110,9 @@ func (driver *Driver) Dump(ctx context.Context, out io.Writer, schemaOnly bool)if err != nil {return "", err}- log.Debug("binlog coordinate at dump time",- zap.String("fileName", binlog.FileName),- zap.Int64("position", binlog.Position))+ slog.Debug("binlog coordinate at dump time",+ slog.String("fileName", binlog.FileName),+ slog.Int64("position", binlog.Position))payload := api.BackupPayload{BinlogInfo: binlog}payloadBytes, err = json.Marshal(payload)@@ -136,7 +135,7 @@ func (driver *Driver) Dump(ctx context.Context, out io.Writer, schemaOnly bool)}defer txn.Rollback()- log.Debug("begin to dump database", zap.String("database", driver.databaseName), zap.Bool("schemaOnly", schemaOnly))+ slog.Debug("begin to dump database", slog.String("database", driver.databaseName), slog.Bool("schemaOnly", schemaOnly))if err := dumpTxn(txn, driver.dbType, driver.databaseName, out, schemaOnly); err != nil {return "", err}diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.goindex 89395d8342..97928484d8 100644--- a/backend/plugin/db/mysql/mysql.go+++ b/backend/plugin/db/mysql/mysql.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""net""strings""time"@@ -12,7 +13,6 @@ import ("github.com/go-sql-driver/mysql""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""golang.org/x/crypto/ssh""google.golang.org/protobuf/types/known/durationpb"@@ -184,7 +184,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, optrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))}totalRowsAffected += rowsAffecteddiff --git a/backend/plugin/db/mysql/restore.go b/backend/plugin/db/mysql/restore.goindex 253c2aca4c..5b15a1bcb5 100644--- a/backend/plugin/db/mysql/restore.go+++ b/backend/plugin/db/mysql/restore.go@@ -14,6 +14,7 @@ import ("encoding/json""fmt""io"+ "log/slog""math""os""os/exec"@@ -24,8 +25,6 @@ import ("strings""time"- "go.uber.org/zap"-"github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -192,9 +191,9 @@ func (driver *Driver) replayBinlogFromDir(ctx context.Context, originalDatabase,mysqlbinlogCmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.dbBinDir), mysqlbinlogArgs...)mysqlCmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQL, driver.dbBinDir), mysqlArgs...)- log.Debug("Start replay binlog commands.",- zap.String("mysqlbinlog", mysqlbinlogCmd.String()),- zap.String("mysql", mysqlCmd.String()))+ slog.Debug("Start replay binlog commands.",+ slog.String("mysqlbinlog", mysqlbinlogCmd.String()),+ slog.String("mysql", mysqlCmd.String()))mysqlRead, err := mysqlbinlogCmd.StdoutPipe()if err != nil {@@ -220,7 +219,7 @@ func (driver *Driver) replayBinlogFromDir(ctx context.Context, originalDatabase,return errors.Wrap(err, "error occurred while waiting for mysqlbinlog to exit")}- log.Debug("Replayed binlog successfully.")+ slog.Debug("Replayed binlog successfully.")return nil}@@ -355,15 +354,15 @@ func (driver *Driver) GetLatestBackupBeforeOrEqualTs(ctx context.Context, backuptargetBinlogCoordinate, err := driver.getBinlogCoordinateByTs(ctx, targetTs, client)if err != nil {- log.Error("Failed to get binlog coordinate by targetTs", zap.Int64("targetTs", targetTs), zap.Error(err))+ slog.Error("Failed to get binlog coordinate by targetTs", slog.Int64("targetTs", targetTs), log.BBError(err))return nil, nil, errors.Wrapf(err, "failed to get binlog coordinate by targetTs %d", targetTs)}- log.Debug("Got binlog coordinate by targetTs", zap.Int64("targetTs", targetTs), zap.Any("binlogCoordinate", *targetBinlogCoordinate))+ slog.Debug("Got binlog coordinate by targetTs", slog.Int64("targetTs", targetTs), slog.Any("binlogCoordinate", *targetBinlogCoordinate))var validBackupList []*store.BackupMessagefor _, b := range backupList {if b.Payload.BinlogInfo.IsEmpty() {- log.Debug("Skip parsing binlog event timestamp of the backup where BinlogInfo is empty", zap.Int("backupId", b.UID), zap.String("backupName", b.Name))+ slog.Debug("Skip parsing binlog event timestamp of the backup where BinlogInfo is empty", slog.Int("backupId", b.UID), slog.String("backupName", b.Name))continue}validBackupList = append(validBackupList, b)@@ -419,9 +418,9 @@ func getLatestBackupBeforeOrEqualBinlogCoord(backupList []*store.BackupMessage,if backup == nil {oldestBackupBinlogCoordinate := backupCoordinateListSorted[len(backupCoordinateListSorted)-1]- log.Error("The target binlog coordinate is earlier than the oldest backup's binlog coordinate",- zap.Any("targetBinlogCoordinate", targetBinlogCoordinate),- zap.Any("oldestBackupBinlogCoordinate", oldestBackupBinlogCoordinate))+ slog.Error("The target binlog coordinate is earlier than the oldest backup's binlog coordinate",+ slog.Any("targetBinlogCoordinate", targetBinlogCoordinate),+ slog.Any("oldestBackupBinlogCoordinate", oldestBackupBinlogCoordinate))return nil, errors.Errorf("the target binlog coordinate %v is earlier than the oldest backup's binlog coordinate %v", targetBinlogCoordinate, oldestBackupBinlogCoordinate)}@@ -436,26 +435,26 @@ func SwapPITRDatabase(ctx context.Context, conn *sql.Conn, database string, suffpitrOldDatabase := util.GetPITROldDatabaseName(database, suffixTs)// Handle the case that the original database does not exist, because user could drop a database and want to restore it.- log.Debug("Checking database exists.", zap.String("database", database))+ slog.Debug("Checking database exists.", slog.String("database", database))dbExists, err := databaseExists(ctx, conn, database)if err != nil {return pitrDatabaseName, pitrOldDatabase, errors.Wrapf(err, "failed to check whether database %q exists", database)}- log.Debug("Turning binlog OFF.")+ slog.Debug("Turning binlog OFF.")// Set OFF the session variable sql_log_bin so that the writes in the following SQL statements will not be recorded in the binlog.if _, err := conn.ExecContext(ctx, "SET sql_log_bin=OFF"); err != nil {return pitrDatabaseName, pitrOldDatabase, err}if !dbExists {- log.Debug("Database does not exist, creating...", zap.String("database", database))+ slog.Debug("Database does not exist, creating...", slog.String("database", database))if _, err := conn.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", database)); err != nil {return pitrDatabaseName, pitrOldDatabase, errors.Wrapf(err, "failed to create non-exist database %q", database)}}- log.Debug("Getting tables in the original and PITR databases.")+ slog.Debug("Getting tables in the original and PITR databases.")tables, err := getTables(ctx, conn, database)if err != nil {return pitrDatabaseName, pitrOldDatabase, errors.Wrapf(err, "failed to get tables of database %q", database)@@ -466,9 +465,9 @@ func SwapPITRDatabase(ctx context.Context, conn *sql.Conn, database string, suff}if len(tables) == 0 && len(tablesPITR) == 0 {- log.Warn("Both databases are empty, skip renaming tables",- zap.String("originalDatabase", database),- zap.String("pitrDatabase", pitrDatabaseName))+ slog.Warn("Both databases are empty, skip renaming tables",+ slog.String("originalDatabase", database),+ slog.String("pitrDatabase", pitrDatabaseName))return pitrDatabaseName, pitrOldDatabase, nil}@@ -484,7 +483,7 @@ func SwapPITRDatabase(ctx context.Context, conn *sql.Conn, database string, sufftableRenames = append(tableRenames, fmt.Sprintf("`%s`.`%s` TO `%s`.`%s`", pitrDatabaseName, table.Name, database, table.Name))}renameStmt := fmt.Sprintf("RENAME TABLE %s;", strings.Join(tableRenames, ", "))- log.Debug("generated RENAME TABLE statement", zap.String("stmt", renameStmt))+ slog.Debug("generated RENAME TABLE statement", slog.String("stmt", renameStmt))if _, err := conn.ExecContext(ctx, renameStmt); err != nil {return pitrDatabaseName, pitrOldDatabase, err@@ -577,7 +576,7 @@ func binlogMetaAreContinuous(files []binlogFileMeta) bool {// Download binlog files on server.func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, metaList []binlogFileMeta, binlogFilesOnServerSorted []BinlogFile, downloadLatestBinlogFile bool, uploader *bbs3.Client) error {if len(binlogFilesOnServerSorted) == 0 {- log.Debug("No binlog file found on server to download")+ slog.Debug("No binlog file found on server to download")return nil}latestBinlogFileOnServer := binlogFilesOnServerSorted[len(binlogFilesOnServerSorted)-1]@@ -593,9 +592,9 @@ func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, metaList_, exist := metaMap[fileOnServer.Seq]if !exist || isLatest {binlogFilePath := filepath.Join(driver.binlogDir, fileOnServer.Name)- log.Debug("Downloading binlog file from MySQL server.", zap.String("path", binlogFilePath), zap.Bool("isLatest", isLatest))+ slog.Debug("Downloading binlog file from MySQL server.", slog.String("path", binlogFilePath), slog.Bool("isLatest", isLatest))if err := driver.downloadBinlogFile(ctx, fileOnServer, isLatest); err != nil {- log.Error("Failed to download binlog file", zap.String("path", binlogFilePath), zap.Error(err))+ slog.Error("Failed to download binlog file", slog.String("path", binlogFilePath), log.BBError(err))return errors.Wrapf(err, "failed to download binlog file %q", binlogFilePath)}if err := driver.writeBinlogMetadataFile(ctx, fileOnServer.Name); err != nil {@@ -627,7 +626,7 @@ func (driver *Driver) FetchAllBinlogFiles(ctx context.Context, downloadLatestBinreturn err}if len(binlogFilesOnServerSorted) == 0 {- log.Debug("No binlog file found on server to download")+ slog.Debug("No binlog file found on server to download")return nil}@@ -657,7 +656,7 @@ func (driver *Driver) syncBinlogMetaFileFromCloud(ctx context.Context, client *bif len(metaListToDownload) == 0 {return nil}- log.Debug(fmt.Sprintf("Downloading %d binlog metadata file from cloud storage", len(metaListToDownload)))+ slog.Debug(fmt.Sprintf("Downloading %d binlog metadata file from cloud storage", len(metaListToDownload)))for _, metaFileName := range metaListToDownload {// Use filepath.Join to compose an OS-specific local file system path.@@ -689,7 +688,7 @@ func (driver *Driver) getBinlogMetaFileListToDownload(ctx context.Context, clienif os.IsNotExist(err) {downloadList = append(downloadList, binlogName)} else {- log.Error("Failed to get stat of local binlog file", zap.String("path", binlogPathLocal))+ slog.Error("Failed to get stat of local binlog file", slog.String("path", binlogPathLocal))}}}@@ -727,25 +726,25 @@ func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownlocmd.Stdout = os.Stderrcmd.Stderr = os.Stderr- log.Debug("Downloading binlog files using mysqlbinlog", zap.String("cmd", cmd.String()))+ slog.Debug("Downloading binlog files using mysqlbinlog", slog.String("cmd", cmd.String()))binlogFilePathTemp := tempBinlogPrefix + binlogFileToDownload.Namedefer os.Remove(binlogFilePathTemp)if err := cmd.Run(); err != nil {- log.Error("Failed to execute mysqlbinlog binary", zap.Error(err))+ slog.Error("Failed to execute mysqlbinlog binary", log.BBError(err))return errors.Wrap(err, "failed to execute mysqlbinlog binary")}- log.Debug("Checking downloaded binlog file stat", zap.String("path", binlogFilePathTemp))+ slog.Debug("Checking downloaded binlog file stat", slog.String("path", binlogFilePathTemp))binlogFileTempInfo, err := os.Stat(binlogFilePathTemp)if err != nil {- log.Error("Failed to get stat of the binlog file.", zap.String("path", binlogFilePathTemp), zap.Error(err))+ slog.Error("Failed to get stat of the binlog file.", slog.String("path", binlogFilePathTemp), log.BBError(err))return errors.Wrapf(err, "failed to get stat of the binlog file %q", binlogFilePathTemp)}if !isLast && binlogFileTempInfo.Size() != binlogFileToDownload.Size {- log.Error("Downloaded archived binlog file size is not equal to size queried on the MySQL server earlier.",- zap.String("binlog", binlogFileToDownload.Name),- zap.Int64("sizeInfo", binlogFileToDownload.Size),- zap.Int64("downloadedSize", binlogFileTempInfo.Size()),+ slog.Error("Downloaded archived binlog file size is not equal to size queried on the MySQL server earlier.",+ slog.String("binlog", binlogFileToDownload.Name),+ slog.Int64("sizeInfo", binlogFileToDownload.Size),+ slog.Int64("downloadedSize", binlogFileTempInfo.Size()),)return errors.Errorf("downloaded archived binlog file %q size %d is not equal to size %d queried on MySQL server earlier", binlogFilePathTemp, binlogFileTempInfo.Size(), binlogFileToDownload.Size)}@@ -775,7 +774,7 @@ func (driver *Driver) uploadBinlogFileToCloud(ctx context.Context, uploader *bbsif _, err := uploader.UploadObject(ctx, path.Join(relativeDir, binlogFileName), binlogFile); err != nil {// Remove the local metadata file so that it can be re-uploaded later.if err := os.Remove(metaFilePath); err != nil {- log.Warn("Failed to remove binlog metadata file %q when error occurs in uploading binlog file", zap.String("binlogFile", binlogFilePath), zap.Error(err))+ slog.Warn("Failed to remove binlog metadata file %q when error occurs in uploading binlog file", slog.String("binlogFile", binlogFilePath), log.BBError(err))}return errors.Wrapf(err, "failed to upload binlog file %q to cloud storage", binlogFileName)}@@ -789,7 +788,7 @@ func (driver *Driver) uploadBinlogFileToCloud(ctx context.Context, uploader *bbsif _, err := uploader.UploadObject(ctx, path.Join(relativeDir, metaFileName), metaFile); err != nil {return errors.Wrapf(err, "failed to upload binlog metadata file %q to cloud storage", metaFileName)}- log.Debug("Successfully uploaded binlog file to cloud storage", zap.String("path", binlogFilePath))+ slog.Debug("Successfully uploaded binlog file to cloud storage", slog.String("path", binlogFilePath))return nil}@@ -912,7 +911,7 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6isLastBinlogFile = truetargetMeta = &metaList[len(metaList)-1]}- log.Debug("Found potential binlog file containing targetTs", zap.String("binlogFile", targetMeta.binlogName), zap.Int64("targetTs", targetTs), zap.Bool("isLastBinlogFile", isLastBinlogFile))+ slog.Debug("Found potential binlog file containing targetTs", slog.String("binlogFile", targetMeta.binlogName), slog.Int64("targetTs", targetTs), slog.Bool("isLastBinlogFile", isLastBinlogFile))if client != nil {// Use filepath.Join to compose an OS-specific local file system path.diff --git a/backend/plugin/db/mysql/role.go b/backend/plugin/db/mysql/role.goindex 58d9857ea9..4df7e1bcef 100644--- a/backend/plugin/db/mysql/role.go+++ b/backend/plugin/db/mysql/role.go@@ -4,12 +4,11 @@ import ("context""database/sql""fmt"+ "log/slog""regexp""strconv""strings"- "go.uber.org/zap"-"github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -389,10 +388,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instancevar err errorusers, err = driver.getUsersFromMySQLUser(ctx)if err != nil {- log.Info("failed to get users", zap.Error(err))+ slog.Info("failed to get users", log.BBError(err))users, err = driver.getUsersFromUserAttributes(ctx)if err != nil {- log.Info("failed to get users", zap.Error(err))+ slog.Info("failed to get users", log.BBError(err))return nil, nil}}@@ -420,7 +419,7 @@ func (driver *Driver) getGrantFromUser(ctx context.Context, name string) ([]strigrantQuery,)if err != nil {- log.Info("failed to get grants", zap.String("user", name), zap.Error(err))+ slog.Info("failed to get grants", slog.String("user", name), log.BBError(err))return nil, nil}defer grantRows.Close()diff --git a/backend/plugin/db/mysql/rollback.go b/backend/plugin/db/mysql/rollback.goindex 1a736e2936..0e882b8157 100644--- a/backend/plugin/db/mysql/rollback.go+++ b/backend/plugin/db/mysql/rollback.go@@ -5,6 +5,7 @@ import ("context""fmt""io"+ "log/slog""os/exec""regexp""strings"@@ -15,9 +16,7 @@ import ("github.com/pingcap/tidb/parser""github.com/pingcap/tidb/parser/ast""github.com/pkg/errors"- "go.uber.org/zap"- "github.com/bytebase/bytebase/backend/common/log"bbparser "github.com/bytebase/bytebase/backend/plugin/parser/sql""github.com/bytebase/bytebase/backend/resources/mysqlutil")@@ -83,7 +82,7 @@ func (driver *Driver) GenerateRollbackSQL(ctx context.Context, binlogSizeLimit iargs = append(args, "--port", driver.connCfg.Port)}cmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.dbBinDir), args...)- log.Debug("mysqlbinlog", zap.String("command", cmd.String()))+ slog.Debug("mysqlbinlog", slog.String("command", cmd.String()))if driver.connCfg.Password != "" {cmd.Env = append(cmd.Env, fmt.Sprintf("MYSQL_PWD=%s", driver.connCfg.Password))}diff --git a/backend/plugin/db/mysql/sync.go b/backend/plugin/db/mysql/sync.goindex bf9e969dd7..0c274896a1 100644--- a/backend/plugin/db/mysql/sync.go+++ b/backend/plugin/db/mysql/sync.go@@ -4,13 +4,13 @@ import ("context""database/sql""fmt"+ "log/slog""math/rand""sort""strconv""strings""time"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/timestamppb""google.golang.org/protobuf/types/known/wrapperspb"@@ -52,11 +52,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, elowerCaseTableNames := 0lowerCaseTableNamesText, err := driver.getServerVariable(ctx, "lower_case_table_names")if err != nil {- log.Debug("failed to get lower_case_table_names variable", zap.Error(err))+ slog.Debug("failed to get lower_case_table_names variable", log.BBError(err))} else {lowerCaseTableNames, err = strconv.Atoi(lowerCaseTableNamesText)if err != nil {- log.Debug("failed to parse lower_case_table_names variable", zap.Error(err))+ slog.Debug("failed to parse lower_case_table_names variable", log.BBError(err))}}@@ -688,7 +688,7 @@ func extractDatabase(defaultDB string, sql string) []string {list, err := parser.ExtractDatabaseList(parser.MySQL, sql, "")if err != nil {// If we can't extract the database, we just use the default database.- log.Debug("extract database failed", zap.Error(err), zap.String("sql", sql))+ slog.Debug("extract database failed", log.BBError(err), slog.String("sql", sql))return []string{defaultDB}}diff --git a/backend/plugin/db/oracle/dump.go b/backend/plugin/db/oracle/dump.goindex 438f81ac63..f8bc359993 100644--- a/backend/plugin/db/oracle/dump.go+++ b/backend/plugin/db/oracle/dump.go@@ -5,12 +5,9 @@ import ("database/sql""fmt""io"+ "log/slog""sort""strings"-- "go.uber.org/zap"-- "github.com/bytebase/bytebase/backend/common/log")// Dump dumps the database.@@ -682,7 +679,7 @@ func (c *mergedConstraintMeta) assembleStatement(out io.Writer) error {return err}default:- log.Warn("Unsupported constraint type", zap.String("type", c.ConstraintType.String))+ slog.Warn("Unsupported constraint type", slog.String("type", c.ConstraintType.String))}return nil}diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.goindex a46fc42ba8..be34ed6761 100644--- a/backend/plugin/db/oracle/oracle.go+++ b/backend/plugin/db/oracle/oracle.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""strconv""strings""time"@@ -12,7 +13,6 @@ import (// Import go-ora Oracle driver."github.com/pkg/errors"go_ora "github.com/sijms/go-ora/v2"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""github.com/bytebase/bytebase/backend/common/log"@@ -116,7 +116,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, optrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/pg/dump.go b/backend/plugin/db/pg/dump.goindex 22eeda711f..91ba0c7978 100644--- a/backend/plugin/db/pg/dump.go+++ b/backend/plugin/db/pg/dump.go@@ -5,6 +5,7 @@ import ("context""fmt""io"+ "log/slog""net""os/exec""path/filepath"@@ -12,7 +13,6 @@ import ("github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db/util"parser "github.com/bytebase/bytebase/backend/plugin/parser/sql")@@ -179,7 +179,7 @@ func (driver *Driver) dumpOneDatabaseWithPgDump(ctx context.Context, database sterrorMsg := make([]byte, 1024)readSize, readErr := errReader.Read(errorMsg)if readSize > 0 {- log.Warn(string(errorMsg))+ slog.Warn(string(errorMsg))allMsg = append(allMsg, errorMsg[0:readSize]...)}if readErr != nil {diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex 7fa303132c..297b8a3bbf 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""net""regexp""strings"@@ -16,7 +17,6 @@ import ("github.com/jackc/pgx/v4/stdlib""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""golang.org/x/crypto/ssh""google.golang.org/protobuf/types/known/durationpb"@@ -181,7 +181,7 @@ func guessDSN(baseConnConfig *pgx.ConnConfig, username string) (string, *pgx.Condefer db.Close()return db.Ping()}(); err != nil {- log.Debug("guessDSN attempt failed", zap.Error(err))+ slog.Debug("guessDSN attempt failed", log.BBError(err))continue}return guessDatabase, &connConfig, nil@@ -358,7 +358,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/redis/redis.go b/backend/plugin/db/redis/redis.goindex eec2934e41..47ca7ee4fa 100644--- a/backend/plugin/db/redis/redis.go+++ b/backend/plugin/db/redis/redis.go@@ -6,6 +6,7 @@ import ("database/sql""fmt""io"+ "log/slog""net""strconv""strings"@@ -14,7 +15,6 @@ import ("github.com/pkg/errors""github.com/redis/go-redis/v9""go.uber.org/multierr"- "go.uber.org/zap""golang.org/x/crypto/ssh""google.golang.org/protobuf/types/known/durationpb"@@ -95,7 +95,7 @@ func (d *Driver) Open(ctx context.Context, _ db.Type, config db.ConnectionConfig// switch to cluster if cluster is enabled.if clusterEnabled {if err := d.rdb.Close(); err != nil {- log.Warn("failed to close redis driver when switching to redis cluster driver", zap.Error(err))+ slog.Warn("failed to close redis driver when switching to redis cluster driver", log.BBError(err))}d.rdb = redis.NewClusterClient(&redis.ClusterOptions{Addrs: []string{addr},diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.goindex 4c4e8f7acd..a67fc91fff 100644--- a/backend/plugin/db/redshift/redshift.go+++ b/backend/plugin/db/redshift/redshift.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""net""regexp""strings"@@ -14,7 +15,6 @@ import ("github.com/jackc/pgx/v4/stdlib""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""golang.org/x/crypto/ssh""google.golang.org/protobuf/types/known/durationpb"@@ -249,7 +249,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatab}// Restore the current transaction role to the current user.if _, err := tx.ExecContext(ctx, "SET SESSION AUTHORIZATION DEFAULT"); err != nil {- log.Warn("Failed to restore the current transaction role to the current user", zap.Error(err))+ slog.Warn("Failed to restore the current transaction role to the current user", log.BBError(err))}if err := tx.Commit(); err != nil {@@ -258,7 +258,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/redshift/sync.go b/backend/plugin/db/redshift/sync.goindex 3743655c51..2533433434 100644--- a/backend/plugin/db/redshift/sync.go+++ b/backend/plugin/db/redshift/sync.go@@ -5,17 +5,16 @@ import ("context""database/sql""fmt"+ "log/slog""regexp""sort""strings""time""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/types/known/wrapperspb""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"@@ -745,7 +744,7 @@ func (driver *Driver) getVersion(ctx context.Context) (string, error) {// We will just return the version string as is.pgVersion, redshiftVersion, err := getPgVersionAndRedshiftVersion(version)if err != nil {- log.Debug("Failed to parse version string", zap.String("version", version))+ slog.Debug("Failed to parse version string", slog.String("version", version))// nolintreturn version, nil}diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.goindex 4344384114..6d456de8f0 100644--- a/backend/plugin/db/risingwave/risingwave.go+++ b/backend/plugin/db/risingwave/risingwave.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""net""regexp""strings"@@ -16,7 +17,6 @@ import ("github.com/jackc/pgx/v4/stdlib""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""golang.org/x/crypto/ssh""google.golang.org/protobuf/types/known/durationpb"@@ -157,7 +157,7 @@ func guessDSN(baseConnConfig *pgx.ConnConfig) (string, *pgx.ConnConfig, error) {defer db.Close()return db.Ping()}(); err != nil {- log.Debug("guessDSN attempt failed", zap.Error(err))+ slog.Debug("guessDSN attempt failed", log.BBError(err))continue}return guessDatabase, &connConfig, nil@@ -306,7 +306,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))} else {totalRowsAffected += rowsAffected}diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.goindex b300997ec0..9080a945e9 100644--- a/backend/plugin/db/snowflake/snowflake.go+++ b/backend/plugin/db/snowflake/snowflake.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""strings""time"@@ -19,7 +20,6 @@ import (v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"snow "github.com/snowflakedb/gosnowflake"- "go.uber.org/zap")var (@@ -51,10 +51,10 @@ func (driver *Driver) Open(_ context.Context, dbType db.Type, config db.Connectireturn nil, err}- log.Debug("Opening Snowflake driver",- zap.String("dsn", loggedDSN),- zap.String("environment", connCtx.EnvironmentID),- zap.String("database", connCtx.InstanceID),+ slog.Debug("Opening Snowflake driver",+ slog.String("dsn", loggedDSN),+ slog.String("environment", connCtx.EnvironmentID),+ slog.String("database", connCtx.InstanceID),)db, err := sql.Open("snowflake", dsn)if err != nil {@@ -94,7 +94,7 @@ func buildSnowflakeDSN(config db.ConnectionConfig) (string, string, error) {redactedDSN, err := snow.DSN(snowConfig)if err != nil {// nolint- log.Warn("failed to build redacted Snowflake DSN", zap.Error(err))+ slog.Warn("failed to build redacted Snowflake DSN", log.BBError(err))return dsn, "", nil}return dsn, redactedDSN, nil@@ -253,7 +253,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, _ drowsAffected, err := result.RowsAffected()// Since we cannot differentiate DDL and DML yet, we have to ignore the error.if err != nil {- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))return 0, nil}return rowsAffected, nildiff --git a/backend/plugin/db/sqlite/sqlite.go b/backend/plugin/db/sqlite/sqlite.goindex 2196e0f683..a1368c3a7c 100644--- a/backend/plugin/db/sqlite/sqlite.go+++ b/backend/plugin/db/sqlite/sqlite.go@@ -5,6 +5,7 @@ import ("context""database/sql""fmt"+ "log/slog""os""path""strings"@@ -13,7 +14,6 @@ import (// Import sqlite3 driver._ "github.com/mattn/go-sqlite3""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""github.com/bytebase/bytebase/backend/common/log"@@ -147,7 +147,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, createDatabrowsAffected, err := sqlResult.RowsAffected()if err != nil {// Since we cannot differentiate DDL and DML yet, we have to ignore the error.- log.Debug("rowsAffected returns error", zap.Error(err))+ slog.Debug("rowsAffected returns error", log.BBError(err))return 0, nil}diff --git a/backend/plugin/db/util/driverutil.go b/backend/plugin/db/util/driverutil.goindex 9eeeba74ae..3940616fd2 100644--- a/backend/plugin/db/util/driverutil.go+++ b/backend/plugin/db/util/driverutil.go@@ -7,6 +7,7 @@ import ("database/sql""fmt""io"+ "log/slog""regexp""strconv""strings"@@ -14,7 +15,6 @@ import ("github.com/blang/semver/v4""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/structpb"@@ -217,7 +217,7 @@ func RunStatement(ctx context.Context, engineType parser.EngineType, conn *sql.C}affectedRows, err := sqlResult.RowsAffected()if err != nil {- log.Info("rowsAffected returns error", zap.Error(err))+ slog.Info("rowsAffected returns error", log.BBError(err))}field := []string{"Affected Rows"}diff --git a/backend/plugin/db/util/ssh.go b/backend/plugin/db/util/ssh.goindex a4e2468cf5..c981f66b52 100644--- a/backend/plugin/db/util/ssh.go+++ b/backend/plugin/db/util/ssh.go@@ -3,10 +3,10 @@ package utilimport ("fmt""io"+ "log/slog""net""os"- "go.uber.org/zap""golang.org/x/crypto/ssh""golang.org/x/crypto/ssh/agent"@@ -79,14 +79,14 @@ func ProxyConnection(sshClient *ssh.Client, listener net.Listener, databaseAddrn, err := conn.Read(buf)if err != nil {if err != io.EOF {- log.Error("proxy source read error", zap.Error(err))+ slog.Error("proxy source read error", log.BBError(err))}return}_, err = targetConn.Write(buf[:n])if err != nil {- log.Error("proxy source write error", zap.Error(err))+ slog.Error("proxy source write error", log.BBError(err))return}}@@ -102,14 +102,14 @@ func ProxyConnection(sshClient *ssh.Client, listener net.Listener, databaseAddrn, err := targetConn.Read(buf)if err != nil {if err != io.EOF {- log.Error("proxy target read error", zap.Error(err))+ slog.Error("proxy target read error", log.BBError(err))}return}_, err = conn.Write(buf[:n])if err != nil {- log.Error("proxy target write error", zap.Error(err))+ slog.Error("proxy target write error", log.BBError(err))return}}diff --git a/backend/plugin/idp/oauth2/oauth2.go b/backend/plugin/idp/oauth2/oauth2.goindex 59fab54c1c..5632eecea9 100644--- a/backend/plugin/idp/oauth2/oauth2.go+++ b/backend/plugin/idp/oauth2/oauth2.go@@ -7,10 +7,10 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""github.com/pkg/errors"- "go.uber.org/zap""golang.org/x/oauth2""github.com/bytebase/bytebase/backend/common"@@ -72,13 +72,13 @@ func (p *IdentityProvider) ExchangeToken(ctx context.Context, redirectURL, codectx = context.WithValue(ctx, oauth2.HTTPClient, p.client)token, err := conf.Exchange(ctx, code)if err != nil {- log.Error("Failed to exchange access token", zap.String("code", code), zap.Error(err))+ slog.Error("Failed to exchange access token", slog.String("code", code), log.BBError(err))return "", errors.Wrap(err, "failed to exchange access token")}accessToken, ok := token.Extra("access_token").(string)if !ok {- log.Error(`Missing "access_token" from authorization response`, zap.String("code", code), zap.Any("token", token))+ slog.Error(`Missing "access_token" from authorization response`, slog.String("code", code), slog.Any("token", token))return "", errors.New(`missing "access_token" from authorization response`)}@@ -95,30 +95,30 @@ func (p *IdentityProvider) UserInfo(token string) (*storepb.IdentityProviderUserreq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))resp, err := p.client.Do(req)if err != nil {- log.Error("Failed to get user information", zap.String("token", token), zap.Error(err))+ slog.Error("Failed to get user information", slog.String("token", token), log.BBError(err))return nil, errors.Wrap(err, "failed to get user information")}defer resp.Body.Close()body, err := io.ReadAll(resp.Body)if err != nil {- log.Error("Failed to read response body", zap.String("token", token), zap.Error(err))+ slog.Error("Failed to read response body", slog.String("token", token), log.BBError(err))return nil, errors.Wrap(err, "failed to read response body")}var claims map[string]anyerr = json.Unmarshal(body, &claims)if err != nil {- log.Error("Failed to unmarshal response body", zap.String("token", token), zap.String("body", string(body)), zap.Error(err))+ slog.Error("Failed to unmarshal response body", slog.String("token", token), slog.String("body", string(body)), log.BBError(err))return nil, errors.Wrap(err, "failed to unmarshal response body")}- log.Debug("User info", zap.Any("claims", claims))+ slog.Debug("User info", slog.Any("claims", claims))userInfo := &storepb.IdentityProviderUserInfo{}if v, ok := idp.GetValueWithKey(claims, p.config.FieldMapping.Identifier).(string); ok {userInfo.Identifier = v}if userInfo.Identifier == "" {- log.Error("Missing identifier in response body", zap.String("token", token), zap.Any("claims", claims), zap.Error(err))+ slog.Error("Missing identifier in response body", slog.String("token", token), slog.Any("claims", claims), log.BBError(err))return nil, errors.Errorf("the field %q is not found in claims or has empty value", p.config.FieldMapping.Identifier)}diff --git a/backend/plugin/idp/oidc/oidc.go b/backend/plugin/idp/oidc/oidc.goindex b495835a73..4f472a06b7 100644--- a/backend/plugin/idp/oidc/oidc.go+++ b/backend/plugin/idp/oidc/oidc.go@@ -4,15 +4,14 @@ package oidcimport ("context""crypto/tls"+ "log/slog""net/http""github.com/coreos/go-oidc""github.com/pkg/errors"- "go.uber.org/zap""golang.org/x/oauth2""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/idp"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -135,7 +134,7 @@ func (p *IdentityProvider) UserInfo(ctx context.Context, token *oauth2.Token, noif err != nil {return nil, errors.Wrap(err, "unmarshal claims")}- log.Debug("User info", zap.Any("claims", claims))+ slog.Debug("User info", slog.Any("claims", claims))userInfo := &storepb.IdentityProviderUserInfo{}if v, ok := idp.GetValueWithKey(claims, p.config.FieldMapping.Identifier).(string); ok {diff --git a/backend/plugin/metric/segment/reporter.go b/backend/plugin/metric/segment/reporter.goindex 02294e2278..5a730daef9 100644--- a/backend/plugin/metric/segment/reporter.go+++ b/backend/plugin/metric/segment/reporter.go@@ -2,10 +2,9 @@package segmentimport (+ "log/slog""time"- "go.uber.org/zap"-"github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/metric"@@ -30,7 +29,7 @@ func NewReporter(key string) metric.Reporter {Logger: &sinkLogger{},})if err != nil {- log.Error("failed to create reporter", zap.Error(err))+ slog.Error("failed to create reporter", log.BBError(err))client = analytics.New(key)}diff --git a/backend/plugin/parser/sql/differ/mysql/differ.go b/backend/plugin/parser/sql/differ/mysql/differ.goindex 8c069a16d9..44a150b653 100644--- a/backend/plugin/parser/sql/differ/mysql/differ.go+++ b/backend/plugin/parser/sql/differ/mysql/differ.go@@ -5,11 +5,10 @@ import ("bytes""fmt""io"+ "log/slog""sort""strings"- "go.uber.org/zap"-"github.com/bytebase/bytebase/backend/common/log""github.com/pingcap/tidb/parser"@@ -934,13 +933,13 @@ func isColumnOptionsEqual(old, new []*ast.ColumnOption) bool {for idx, oldOption := range oldNormalizeOptions {oldOptionStr, err := toString(oldOption)if err != nil {- log.Error("failed to convert old column option to string", zap.Error(err))+ slog.Error("failed to convert old column option to string", log.BBError(err))return false}newOption := newNormalizeOptions[idx]newOptionStr, err := toString(newOption)if err != nil {- log.Error("failed to convert new column option to string", zap.Error(err))+ slog.Error("failed to convert new column option to string", log.BBError(err))return false}if oldOptionStr != newOptionStr {@@ -1057,12 +1056,12 @@ func isKeyPartEqual(old, new []*ast.IndexPartSpecification) bool {if oldKeyPart.Expr != nil && newKeyPart.Expr != nil {oldKeyPartStr, err := toString(oldKeyPart.Expr)if err != nil {- log.Error("failed to convert old key part to string", zap.Error(err))+ slog.Error("failed to convert old key part to string", log.BBError(err))return false}newKeyPartStr, err := toString(newKeyPart.Expr)if err != nil {- log.Error("failed to convert new key part to string", zap.Error(err))+ slog.Error("failed to convert new key part to string", log.BBError(err))return false}return oldKeyPartStr == newKeyPartStr@@ -1196,12 +1195,12 @@ func isCheckConstraintEqual(old, new *ast.Constraint) bool {oldExpr, err := toString(trimParentheses(old.Expr))if err != nil {- log.Error("failed to convert old check constraint expression to string", zap.Error(err))+ slog.Error("failed to convert old check constraint expression to string", log.BBError(err))return false}newExpr, err := toString(trimParentheses(new.Expr))if err != nil {- log.Error("failed to convert new check constraint expression to string", zap.Error(err))+ slog.Error("failed to convert new check constraint expression to string", log.BBError(err))return false}return oldExpr == newExpr@@ -1521,24 +1520,24 @@ func (diff *diffNode) isViewEqual(old, new *ast.CreateViewStmt) bool {if diff.ignoreCaseSensitive {oldViewStr, err := toLowerNameString(old)if err != nil {- log.Error("fail to convert old view to string", zap.Error(err))+ slog.Error("fail to convert old view to string", log.BBError(err))return false}newViewStr, err := toLowerNameString(new)if err != nil {- log.Error("fail to convert new view to string", zap.Error(err))+ slog.Error("fail to convert new view to string", log.BBError(err))return false}return oldViewStr == newViewStr}oldViewStr, err := toString(old)if err != nil {- log.Error("fail to convert old view to string", zap.Error(err))+ slog.Error("fail to convert old view to string", log.BBError(err))return false}newViewStr, err := toString(new)if err != nil {- log.Error("fail to convert new view to string", zap.Error(err))+ slog.Error("fail to convert new view to string", log.BBError(err))return false}return oldViewStr == newViewStrdiff --git a/backend/plugin/parser/sql/validate_sql_for_editor.go b/backend/plugin/parser/sql/validate_sql_for_editor.goindex 207701db9b..61fe318c83 100644--- a/backend/plugin/parser/sql/validate_sql_for_editor.go+++ b/backend/plugin/parser/sql/validate_sql_for_editor.go@@ -3,12 +3,12 @@ package parserimport ("bytes""encoding/json"+ "log/slog""regexp""strings"pgquery "github.com/pganalyze/pg_query_go/v4""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log")@@ -38,7 +38,7 @@ func ValidateSQLForEditor(engine EngineType, statement string) bool {func standardValidateSQLForEditor(statement string) bool {textWithoutQuotedAndComment, err := removeQuotedTextAndComment(Standard, statement)if err != nil {- log.Debug("Failed to remove quoted text and comment", zap.String("statement", statement), zap.Error(err))+ slog.Debug("Failed to remove quoted text and comment", slog.String("statement", statement), log.BBError(err))return false}@@ -53,7 +53,7 @@ func standardValidateSQLForEditor(statement string) bool {func mysqlValidateSQLForEditor(statement string) bool {textWithoutQuotedAndComment, err := removeQuotedTextAndComment(MySQL, statement)if err != nil {- log.Debug("Failed to remove quoted text and comment", zap.String("statement", statement), zap.Error(err))+ slog.Debug("Failed to remove quoted text and comment", slog.String("statement", statement), log.BBError(err))return false}@@ -67,7 +67,7 @@ func mysqlValidateSQLForEditor(statement string) bool {func postgresValidateSQLForEditor(statement string) bool {jsonText, err := pgquery.ParseToJSON(statement)if err != nil {- log.Debug("Failed to parse statement to JSON", zap.String("statement", statement), zap.Error(err))+ slog.Debug("Failed to parse statement to JSON", slog.String("statement", statement), log.BBError(err))return false}@@ -92,7 +92,7 @@ func postgresValidateSQLForEditor(statement string) bool {var jsonData map[string]anyif err := json.Unmarshal([]byte(jsonText), &jsonData); err != nil {- log.Debug("Failed to unmarshal JSON", zap.String("jsonText", jsonText), zap.Error(err))+ slog.Debug("Failed to unmarshal JSON", slog.String("jsonText", jsonText), log.BBError(err))return false}diff --git a/backend/plugin/storage/s3/s3_test.go b/backend/plugin/storage/s3/s3_test.goindex fe433aca2f..84ad4cbd04 100644--- a/backend/plugin/storage/s3/s3_test.go+++ b/backend/plugin/storage/s3/s3_test.go@@ -3,14 +3,12 @@ package s3import ("bytes""context"+ "log/slog""os""testing""github.com/aws/aws-sdk-go-v2/aws""github.com/stretchr/testify/require"- "go.uber.org/zap"-- "github.com/bytebase/bytebase/backend/common/log")const (@@ -38,7 +36,7 @@ func TestS3Operations(t *testing.T) {list, err := client.ListObjects(ctx, "backup/")a.NoError(err)for _, obj := range list {- log.Info("Object", zap.String("Key", *obj.Key), zap.Time("LastModified", *obj.LastModified))+ slog.Info("Object", slog.String("Key", *obj.Key), slog.Time("LastModified", *obj.LastModified))}})@@ -47,7 +45,7 @@ func TestS3Operations(t *testing.T) {blob := bytes.NewReader(buf)resp, err := client.UploadObject(ctx, "backup/test/blob", blob)a.NoError(err)- log.Info("Uploaded", zap.String("name", *resp.Key))+ slog.Info("Uploaded", slog.String("name", *resp.Key))})t.Run("DownloadObjects", func(t *testing.T) {@@ -55,12 +53,12 @@ func TestS3Operations(t *testing.T) {a.NoError(err)n, err := client.DownloadObject(ctx, "backup/test/blob", file)a.NoError(err)- log.Info("Downloaded", zap.Int64("length", n))+ slog.Info("Downloaded", slog.Int64("length", n))})t.Run("DeleteObjects", func(t *testing.T) {resp, err := client.DeleteObjects(ctx, "backup/test/blob")a.NoError(err)- log.Info("Deleted", zap.Any("meta", resp.ResultMetadata))+ slog.Info("Deleted", slog.Any("meta", resp.ResultMetadata))})}diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.goindex 5a872569da..8da3f18314 100644--- a/backend/plugin/vcs/azure/azure.go+++ b/backend/plugin/vcs/azure/azure.go@@ -7,6 +7,7 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""net/url""path/filepath"@@ -15,11 +16,9 @@ import ("time""github.com/pkg/errors"- "go.uber.org/zap""golang.org/x/exp/slices""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/vcs""github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth")@@ -487,7 +486,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.Ofor _, r := range l.Value {if r.Project.State != "wellFormed" {- log.Debug("Skip the repository whose project is not wellFormed", zap.String("organization", organization), zap.String("project", r.Project.Name), zap.String("repository", r.Name))+ slog.Debug("Skip the repository whose project is not wellFormed", slog.String("organization", organization), slog.String("project", r.Project.Name), slog.String("repository", r.Name))}result = append(result, &vcs.Repository{@@ -813,7 +812,7 @@ func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.Oauthreturn errors.Wrapf(err, "POST %s", url)}if code == http.StatusBadRequest {- log.Info("Failed to create file, retrying", zap.String("url", url), zap.String("body", string(body)))+ slog.Info("Failed to create file, retrying", slog.String("url", url), slog.String("body", string(body)))continue}if code != http.StatusCreated {diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.goindex 5e3548a450..db3bdad734 100644--- a/backend/plugin/vcs/github/github.go+++ b/backend/plugin/vcs/github/github.go@@ -9,6 +9,7 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""net/url""strconv"@@ -19,7 +20,6 @@ import ("golang.org/x/crypto/nacl/box""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -780,20 +780,20 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.Oautfor _, file := range allPRFiles {u, err := url.Parse(file.ContentsURL)if err != nil {- log.Debug("Failed to parse content url for file",- zap.String("content_url", file.ContentsURL),- zap.String("file", file.FileName),- zap.Error(err),+ slog.Debug("Failed to parse content url for file",+ slog.String("content_url", file.ContentsURL),+ slog.String("file", file.FileName),+ log.BBError(err),)continue}m, err := url.ParseQuery(u.RawQuery)if err != nil {- log.Debug("Failed to parse query for file",- zap.String("content_url", file.ContentsURL),- zap.String("file", file.FileName),- zap.Error(err),+ slog.Debug("Failed to parse query for file",+ slog.String("content_url", file.ContentsURL),+ slog.String("file", file.FileName),+ log.BBError(err),)continue}diff --git a/backend/plugin/vcs/internal/oauth/oauth.go b/backend/plugin/vcs/internal/oauth/oauth.goindex 108021b6c0..6923559d37 100644--- a/backend/plugin/vcs/internal/oauth/oauth.go+++ b/backend/plugin/vcs/internal/oauth/oauth.go@@ -7,11 +7,11 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""strings""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log")@@ -123,7 +123,7 @@ func retry(ctx context.Context, client *http.Client, token *string, tokenRefreshreturn 0, nil, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)}if err := resp.Body.Close(); err != nil {- log.Warn("failed to close resp body", zap.Error(err))+ slog.Warn("failed to close resp body", log.BBError(err))}if err = getOAuthErrorDetails(resp.StatusCode, body); err != nil {diff --git a/backend/plugin/vcs/util.go b/backend/plugin/vcs/util.goindex 99805d1b17..89c979c013 100644--- a/backend/plugin/vcs/util.go+++ b/backend/plugin/vcs/util.go@@ -2,12 +2,10 @@package vcsimport (+ "log/slog""strings""github.com/pkg/errors"- "go.uber.org/zap"-- "github.com/bytebase/bytebase/backend/common/log")// Branch is the helper function returns the branch name from reference name.@@ -64,9 +62,9 @@ func (p PushEvent) GetDistinctFileList() []DistinctFileItem {// Use list instead of map because we need to maintain the relative commit order in the source branch.var distinctFileList []DistinctFileItemfor _, commit := range p.CommitList {- log.Debug("Pre-processing commit to dedup migration files...",- zap.String("id", commit.ID),- zap.String("title", commit.Title),+ slog.Debug("Pre-processing commit to dedup migration files...",+ slog.String("id", commit.ID),+ slog.String("title", commit.Title),)addDistinctFile := func(fileName string, itemType FileItemType) {diff --git a/backend/resources/mongoutil/mongoutil.go b/backend/resources/mongoutil/mongoutil.goindex 988c2d9cbb..c9536348e0 100644--- a/backend/resources/mongoutil/mongoutil.go+++ b/backend/resources/mongoutil/mongoutil.go@@ -3,6 +3,7 @@ package mongoutilimport ("fmt"+ "log/slog""os""path""runtime"@@ -10,7 +11,6 @@ import ("github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/resources/utils")@@ -51,7 +51,7 @@ func Install(resourceDir string) (string, error) {return "", errors.Wrapf(err, "failed to check binary directory path %q", mongoutilDir)}// Install if not exist yet- log.Info("Installing MongoDB utilities, it may take about several minutes...")+ slog.Info("Installing MongoDB utilities, it may take about several minutes...")if err := installImpl(resourceDir, mongoutilDir, tarName, version); err != nil {return "", errors.Wrap(err, "cannot install mongoutil")}diff --git a/backend/resources/mysqlutil/mysqlutil.go b/backend/resources/mysqlutil/mysqlutil.goindex a39da8dc31..d6655edcdf 100644--- a/backend/resources/mysqlutil/mysqlutil.go+++ b/backend/resources/mysqlutil/mysqlutil.go@@ -3,6 +3,7 @@ package mysqlutilimport ("fmt"+ "log/slog""os""path""path/filepath"@@ -11,7 +12,6 @@ import ("github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/resources/utils")@@ -70,7 +70,7 @@ func Install(resourceDir string) (string, error) {return "", errors.Wrapf(err, "failed to check binary directory path %q", mysqlutilDir)}// Install if not exist yet- log.Info("Installing MySQL utilities...")+ slog.Info("Installing MySQL utilities...")if err := installImpl(resourceDir, mysqlutilDir, tarName, version); err != nil {return "", errors.Wrap(err, "cannot install mysqlutil")}diff --git a/backend/resources/postgres/postgres.go b/backend/resources/postgres/postgres.goindex e00d2e4a1b..360a9bf35d 100644--- a/backend/resources/postgres/postgres.go+++ b/backend/resources/postgres/postgres.go@@ -10,6 +10,7 @@ import ("context""fmt"+ "log/slog""os""os/exec""os/user"@@ -22,7 +23,6 @@ import ("testing""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -76,7 +76,7 @@ func Install(resourceDir string) (string, error) {needInstall = true}if needInstall {- log.Info("Installing PostgreSQL utilities...")+ slog.Info("Installing PostgreSQL utilities...")// The ordering below made Postgres installation atomic.tmpDir := path.Join(resourceDir, fmt.Sprintf("tmp-%s", version))if err := installInDir(tarName, tmpDir); err != nil {@@ -184,7 +184,7 @@ func InitDB(pgBinDir, pgDataDir, pgUser string) error {dirListToChown = append(dirListToChown, path)path = filepath.Dir(path)}- log.Debug("Data directory list to Chown", zap.Any("dirListToChown", dirListToChown))+ slog.Debug("Data directory list to Chown", slog.Any("dirListToChown", dirListToChown))if err := os.MkdirAll(pgDataDir, 0700); err != nil {return errors.Wrapf(err, "failed to make postgres data directory %q", pgDataDir)@@ -209,9 +209,9 @@ func InitDB(pgBinDir, pgDataDir, pgUser string) error {Setpgid: true,Credential: &syscall.Credential{Uid: uint32(uid)},}- log.Info(fmt.Sprintf("Recursively change owner of data directory %q to bytebase...", pgDataDir))+ slog.Info(fmt.Sprintf("Recursively change owner of data directory %q to bytebase...", pgDataDir))for _, dir := range dirListToChown {- log.Info(fmt.Sprintf("Change owner of %q to bytebase", dir))+ slog.Info(fmt.Sprintf("Change owner of %q to bytebase", dir))if err := os.Chown(dir, int(uid), int(gid)); err != nil {return errors.Wrapf(err, "failed to change owner of %q to bytebase", dir)}@@ -221,11 +221,11 @@ func InitDB(pgBinDir, pgDataDir, pgUser string) error {// Suppress log spamp.Stdout = nilp.Stderr = os.Stderr- log.Info("-----Postgres initdb BEGIN-----")+ slog.Info("-----Postgres initdb BEGIN-----")if err := p.Run(); err != nil {return errors.Wrapf(err, "failed to initdb %q", p.String())}- log.Info("-----Postgres initdb END-----")+ slog.Info("-----Postgres initdb END-----")return nil}@@ -423,7 +423,7 @@ func StartSampleInstance(ctx context.Context, pgBinDir, pgDataDir string, port i}if err := turnOnPGStateStatements(pgDataDir); err != nil {- log.Warn("Failed to turn on pg_stat_statements", zap.Error(err))+ slog.Warn("Failed to turn on pg_stat_statements", log.BBError(err))}if err := Start(port, pgBinDir, pgDataDir, mode == common.ReleaseModeDev /* serverLog */); err != nil {@@ -436,7 +436,7 @@ func StartSampleInstance(ctx context.Context, pgBinDir, pgDataDir string, port i}if err := createPGStatStatementsExtension(ctx, SampleUser, host, strconv.Itoa(port), SampleDatabase); err != nil {- log.Warn("Failed to create pg_stat_statements extension", zap.Error(err))+ slog.Warn("Failed to create pg_stat_statements extension", log.BBError(err))}return nil@@ -464,7 +464,7 @@ func createPGStatStatementsExtension(ctx context.Context, pgUser, host, port, daif _, err := driver.Execute(ctx, "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;", false, db.ExecuteOptions{}); err != nil {return errors.Wrapf(err, "failed to create pg_stat_statements extension")}- log.Info("Successfully created pg_stat_statements extension")+ slog.Info("Successfully created pg_stat_statements extension")return nil}@@ -513,7 +513,7 @@ func turnOnPGStateStatements(pgDataDir string) error {}}- log.Info("Successfully added pg_stat_statements to postgresql.conf file")+ slog.Info("Successfully added pg_stat_statements to postgresql.conf file")return nil}diff --git a/backend/runner/anomaly/scanner.go b/backend/runner/anomaly/scanner.goindex 08130cb5b5..fa9fd59b1a 100644--- a/backend/runner/anomaly/scanner.go+++ b/backend/runner/anomaly/scanner.go@@ -5,11 +5,11 @@ import ("context""encoding/json""fmt"+ "log/slog""sync""time""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -46,13 +46,13 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(anomalyScanInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Anomaly scanner started and will run every %v", anomalyScanInterval))+ slog.Debug(fmt.Sprintf("Anomaly scanner started and will run every %v", anomalyScanInterval))runningTasks := make(map[int]bool)mu := sync.RWMutex{}for {select {case <-ticker.C:- log.Debug("New anomaly scanner round started...")+ slog.Debug("New anomaly scanner round started...")func() {defer func() {if r := recover(); r != nil {@@ -60,7 +60,7 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {if !ok {err = errors.Errorf("%v", r)}- log.Error("Anomaly scanner PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Anomaly scanner PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()@@ -68,7 +68,7 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {environments, err := s.store.ListEnvironmentV2(ctx, &store.FindEnvironmentMessage{})if err != nil {- log.Error("Failed to retrieve instance list", zap.Error(err))+ slog.Error("Failed to retrieve instance list", log.BBError(err))return}@@ -76,9 +76,9 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {for _, environment := range environments {policy, err := s.store.GetBackupPlanPolicyByEnvID(ctx, environment.UID)if err != nil {- log.Error("Failed to retrieve backup policy",- zap.String("environment", environment.Title),- zap.Error(err))+ slog.Error("Failed to retrieve backup policy",+ slog.String("environment", environment.Title),+ log.BBError(err))return}backupPlanPolicyMap[environment.UID] = policy@@ -86,7 +86,7 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {instances, err := s.store.ListInstancesV2(ctx, &store.FindInstanceMessage{})if err != nil {- log.Error("Failed to retrieve instance list", zap.Error(err))+ slog.Error("Failed to retrieve instance list", log.BBError(err))return}@@ -112,7 +112,7 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {// Do NOT use go-routine otherwise would cause "database locked" in underlying SQLitefunc(environment *store.EnvironmentMessage, instance *store.InstanceMessage) {- log.Debug("Scan instance anomaly", zap.String("instance", instance.ResourceID))+ slog.Debug("Scan instance anomaly", slog.String("instance", instance.ResourceID))defer func() {mu.Lock()delete(runningTasks, instance.UID)@@ -123,9 +123,9 @@ func (s *Scanner) Run(ctx context.Context, wg *sync.WaitGroup) {databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID})if err != nil {- log.Error("Failed to retrieve database list",- zap.String("instance", instance.ResourceID),- zap.Error(err))+ slog.Error("Failed to retrieve database list",+ slog.String("instance", instance.ResourceID),+ log.BBError(err))return}for _, database := range databases {@@ -158,20 +158,20 @@ func (s *Scanner) checkInstanceAnomaly(ctx context.Context, instance *store.Inst}payload, err := json.Marshal(anomalyPayload)if err != nil {- log.Error("Failed to marshal anomaly payload",- zap.String("instance", instance.ResourceID),- zap.String("type", string(api.AnomalyInstanceConnection)),- zap.Error(err))+ slog.Error("Failed to marshal anomaly payload",+ slog.String("instance", instance.ResourceID),+ slog.String("type", string(api.AnomalyInstanceConnection)),+ log.BBError(err))} else {if _, err = s.store.UpsertActiveAnomalyV2(ctx, api.SystemBotID, &store.AnomalyMessage{InstanceID: instance.ResourceID,Type: api.AnomalyInstanceConnection,Payload: string(payload),}); err != nil {- log.Error("Failed to create anomaly",- zap.String("instance", instance.ResourceID),- zap.String("type", string(api.AnomalyInstanceConnection)),- zap.Error(err))+ slog.Error("Failed to create anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("type", string(api.AnomalyInstanceConnection)),+ log.BBError(err))}}return@@ -183,10 +183,10 @@ func (s *Scanner) checkInstanceAnomaly(ctx context.Context, instance *store.InstType: api.AnomalyInstanceConnection,})if err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to close anomaly",- zap.String("instance", instance.ResourceID),- zap.String("type", string(api.AnomalyInstanceConnection)),- zap.Error(err))+ slog.Error("Failed to close anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("type", string(api.AnomalyInstanceConnection)),+ log.BBError(err))}}@@ -200,11 +200,11 @@ func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.Inst}payload, err := json.Marshal(anomalyPayload)if err != nil {- log.Error("Failed to marshal anomaly payload",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseConnection)),- zap.Error(err))+ slog.Error("Failed to marshal anomaly payload",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseConnection)),+ log.BBError(err))} else {if _, err = s.store.UpsertActiveAnomalyV2(ctx, api.SystemBotID, &store.AnomalyMessage{InstanceID: instance.ResourceID,@@ -212,11 +212,11 @@ func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.InstType: api.AnomalyDatabaseConnection,Payload: string(payload),}); err != nil {- log.Error("Failed to create anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseConnection)),- zap.Error(err))+ slog.Error("Failed to create anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseConnection)),+ log.BBError(err))}}return@@ -227,11 +227,11 @@ func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.InstType: api.AnomalyDatabaseConnection,})if err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to close anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseConnection)),- zap.Error(err))+ slog.Error("Failed to close anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseConnection)),+ log.BBError(err))}}@@ -244,10 +244,10 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.Envschedule := api.BackupPlanPolicyScheduleUnsetbackupSetting, err := s.store.GetBackupSettingV2(ctx, database.UID)if err != nil {- log.Error("Failed to retrieve backup setting",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.Error(err))+ slog.Error("Failed to retrieve backup setting",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ log.BBError(err))return}@@ -283,11 +283,11 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.Envif backupPolicyAnomalyPayload != nil {payload, err := json.Marshal(*backupPolicyAnomalyPayload)if err != nil {- log.Error("Failed to marshal anomaly payload",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseBackupPolicyViolation)),- zap.Error(err))+ slog.Error("Failed to marshal anomaly payload",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseBackupPolicyViolation)),+ log.BBError(err))} else {if _, err = s.store.UpsertActiveAnomalyV2(ctx, api.SystemBotID, &store.AnomalyMessage{InstanceID: instance.ResourceID,@@ -295,11 +295,11 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.EnvType: api.AnomalyDatabaseBackupPolicyViolation,Payload: string(payload),}); err != nil {- log.Error("Failed to create anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseBackupPolicyViolation)),- zap.Error(err))+ slog.Error("Failed to create anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseBackupPolicyViolation)),+ log.BBError(err))}}} else {@@ -308,11 +308,11 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.EnvType: api.AnomalyDatabaseBackupPolicyViolation,})if err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to close anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseBackupPolicyViolation)),- zap.Error(err))+ slog.Error("Failed to close anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseBackupPolicyViolation)),+ log.BBError(err))}}}@@ -338,10 +338,10 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.Env}backupList, err := s.store.ListBackupV2(ctx, backupFind)if err != nil {- log.Error("Failed to retrieve backup list",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.Error(err))+ slog.Error("Failed to retrieve backup list",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ log.BBError(err))}hasValidBackup := false@@ -365,11 +365,11 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.Envif backupMissingAnomalyPayload != nil {payload, err := json.Marshal(*backupMissingAnomalyPayload)if err != nil {- log.Error("Failed to marshal anomaly payload",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseBackupMissing)),- zap.Error(err))+ slog.Error("Failed to marshal anomaly payload",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseBackupMissing)),+ log.BBError(err))} else {if _, err = s.store.UpsertActiveAnomalyV2(ctx, api.SystemBotID, &store.AnomalyMessage{InstanceID: instance.ResourceID,@@ -377,11 +377,11 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.EnvType: api.AnomalyDatabaseBackupMissing,Payload: string(payload),}); err != nil {- log.Error("Failed to create anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseBackupMissing)),- zap.Error(err))+ slog.Error("Failed to create anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseBackupMissing)),+ log.BBError(err))}}} else {@@ -390,11 +390,11 @@ func (s *Scanner) checkBackupAnomaly(ctx context.Context, environment *store.EnvType: api.AnomalyDatabaseBackupMissing,})if err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to close anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseBackupMissing)),- zap.Error(err))+ slog.Error("Failed to close anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseBackupMissing)),+ log.BBError(err))}}}diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex 8ea70388a7..cf8148bc93 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""reflect""sort""strconv"@@ -15,7 +16,6 @@ import ("github.com/google/cel-go/cel""github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""google.golang.org/protobuf/encoding/protojson"v1 "github.com/bytebase/bytebase/backend/api/v1"@@ -64,7 +64,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(approvalRunnerInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Approval runner started and will run every %v", approvalRunnerInterval))+ slog.Debug(fmt.Sprintf("Approval runner started and will run every %v", approvalRunnerInterval))r.retryFindApprovalTemplate(ctx)for {select {@@ -94,7 +94,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {return errs}(); err != nil {- log.Error("approval runner", zap.Error(err))+ slog.Error("approval runner", log.BBError(err))}case <-ctx.Done():@@ -109,12 +109,12 @@ func (r *Runner) retryFindApprovalTemplate(ctx context.Context) {})if err != nil {err := errors.Wrap(err, "failed to list issues")- log.Error("failed to retry finding approval template", zap.Error(err))+ slog.Error("failed to retry finding approval template", log.BBError(err))}for _, issue := range issues {payload := &storepb.IssuePayload{}if err := protojson.Unmarshal([]byte(issue.Payload), payload); err != nil {- log.Error("failed to retry finding approval template", zap.Int("issueID", issue.UID), zap.Error(err))+ slog.Error("failed to retry finding approval template", slog.Int("issueID", issue.UID), log.BBError(err))continue}if payload.Approval == nil || !payload.Approval.ApprovalFindingDone {@@ -191,7 +191,7 @@ func (r *Runner) findApprovalTemplateForIssue(ctx context.Context, issue *store.Level: api.ActivityInfo,Comment: fmt.Sprintf("Granted %s to %s (%s).", newUser.Name, newUser.Email, payload.GrantRequest.Role),}, &activity.Metadata{}); err != nil {- log.Warn("Failed to create project activity", zap.Error(err))+ slog.Warn("Failed to create project activity", log.BBError(err))}if err := utils.ChangeIssueStatus(ctx, r.store, r.activityManager, issue, api.IssueDone, api.SystemBotID, ""); err != nil {return false, errors.Wrap(err, "failed to update issue status")@@ -234,7 +234,7 @@ func (r *Runner) findApprovalTemplateForIssue(ctx context.Context, issue *store.return nil}(); err != nil {- log.Error("failed to create activity after approving review", zap.Error(err))+ slog.Error("failed to create activity after approving review", log.BBError(err))}if err := func() error {@@ -272,7 +272,7 @@ func (r *Runner) findApprovalTemplateForIssue(ctx context.Context, issue *store.return nil}(); err != nil {- log.Error("failed to create approval step pending activity after creating review", zap.Error(err))+ slog.Error("failed to create approval step pending activity after creating review", log.BBError(err))}return true, nil@@ -867,7 +867,7 @@ func getTaskRiskLevel(ctx context.Context, s *store.Store, issue *store.IssueMesif affectedRowsReportResult[i].Code == common.Ok.Int() {affectedRows, err := strconv.ParseInt(affectedRowsReportResult[i].Content, 10, 64)if err != nil {- log.Warn("failed to convert affectedRows to int64, will use 0 as the value of affected_rows", zap.Error(err))+ slog.Warn("failed to convert affectedRows to int64, will use 0 as the value of affected_rows", log.BBError(err))} else {args["affected_rows"] = affectedRows}diff --git a/backend/runner/backuprun/runner.go b/backend/runner/backuprun/runner.goindex 19d924ba8f..8f58b206b9 100644--- a/backend/runner/backuprun/runner.go+++ b/backend/runner/backuprun/runner.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""math""net/http""os"@@ -15,7 +16,6 @@ import ("github.com/gosimple/slug""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -60,7 +60,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(r.profile.BackupRunnerInterval)defer ticker.Stop()defer wg.Done()- log.Debug("Auto backup runner started", zap.Duration("interval", r.profile.BackupRunnerInterval))+ slog.Debug("Auto backup runner started", slog.Duration("interval", r.profile.BackupRunnerInterval))for {select {case <-ticker.C:@@ -71,7 +71,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {if !ok {err = errors.Errorf("%v", r)}- log.Error("Auto backup runner PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Auto backup runner PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()r.startAutoBackups(ctx)@@ -91,7 +91,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {func (r *Runner) purgeExpiredBackupData(ctx context.Context) {backupSettingList, err := r.store.ListBackupSettingV2(ctx, &store.FindBackupSettingMessage{})if err != nil {- log.Error("Failed to find all the backup settings.", zap.Error(err))+ slog.Error("Failed to find all the backup settings.", log.BBError(err))return}@@ -105,16 +105,16 @@ func (r *Runner) purgeExpiredBackupData(ctx context.Context) {RowStatus: &statusNormal,})if err != nil {- log.Error("Failed to get backups for database.", zap.Int("databaseID", bs.DatabaseUID))+ slog.Error("Failed to get backups for database.", slog.Int("databaseID", bs.DatabaseUID))return}for _, backup := range backupList {backupTime := time.Unix(backup.UpdatedTs, 0)expireTime := backupTime.Add(time.Duration(bs.RetentionPeriodTs) * time.Second)if time.Now().After(expireTime) {- log.Debug("Purging expired backup", zap.Int("databaseID", backup.DatabaseUID), zap.String("backup", backup.Name), zap.String("storageBackend", string(backup.StorageBackend)))+ slog.Debug("Purging expired backup", slog.Int("databaseID", backup.DatabaseUID), slog.String("backup", backup.Name), slog.String("storageBackend", string(backup.StorageBackend)))if err := r.purgeBackup(ctx, backup); err != nil {- log.Error("Failed to purge backup", zap.String("backup", backup.Name), zap.Error(err))+ slog.Error("Failed to purge backup", slog.String("backup", backup.Name), log.BBError(err))}}}@@ -122,7 +122,7 @@ func (r *Runner) purgeExpiredBackupData(ctx context.Context) {instanceList, err := r.store.ListInstancesV2(ctx, &store.FindInstanceMessage{})if err != nil {- log.Error("Failed to find non-archived instances.", zap.Error(err))+ slog.Error("Failed to find non-archived instances.", log.BBError(err))return}@@ -132,14 +132,14 @@ func (r *Runner) purgeExpiredBackupData(ctx context.Context) {}maxRetentionPeriodTs, err := r.getMaxRetentionPeriodTsForMySQLInstance(ctx, instance)if err != nil {- log.Error("Failed to get max retention period for MySQL instance", zap.String("instance", instance.Title), zap.Error(err))+ slog.Error("Failed to get max retention period for MySQL instance", slog.String("instance", instance.Title), log.BBError(err))continue}if maxRetentionPeriodTs == math.MaxInt {continue}if err := r.purgeBinlogFiles(ctx, instance.UID, maxRetentionPeriodTs); err != nil {- log.Error("Failed to purge binlog files for instance", zap.String("instance", instance.Title), zap.Int("retentionPeriodTs", maxRetentionPeriodTs), zap.Error(err))+ slog.Error("Failed to purge binlog files for instance", slog.String("instance", instance.Title), slog.Int("retentionPeriodTs", maxRetentionPeriodTs), log.BBError(err))}}}@@ -147,7 +147,7 @@ func (r *Runner) purgeExpiredBackupData(ctx context.Context) {func (r *Runner) getMaxRetentionPeriodTsForMySQLInstance(ctx context.Context, instance *store.InstanceMessage) (int, error) {backupSettingList, err := r.store.ListBackupSettingV2(ctx, &store.FindBackupSettingMessage{InstanceUID: &instance.UID})if err != nil {- log.Error("Failed to find backup settings for instance.", zap.String("instance", instance.Title), zap.Error(err))+ slog.Error("Failed to find backup settings for instance.", slog.String("instance", instance.Title), log.BBError(err))return 0, errors.Wrapf(err, "failed to find backup settings for instance %q", instance.Title)}maxRetentionPeriodTs := math.MaxInt@@ -185,7 +185,7 @@ func (r *Runner) purgeBinlogFilesOnCloud(ctx context.Context, binlogDir string,}}if len(purgeBinlogPathList) > 0 {- log.Debug(fmt.Sprintf("Deleting %d expired binlog files from the cloud storage.", len(purgeBinlogPathList)))+ slog.Debug(fmt.Sprintf("Deleting %d expired binlog files from the cloud storage.", len(purgeBinlogPathList)))if _, err := r.s3Client.DeleteObjects(ctx, purgeBinlogPathList...); err != nil {return errors.Wrapf(err, "failed to delete %d expired binlog files from the cloud storage", len(purgeBinlogPathList))}@@ -208,20 +208,20 @@ func (*Runner) purgeBinlogFilesLocal(binlogDir string, retentionPeriodTs int) er// This is not accurate and gives about 10 minutes (backup runner interval) more retention time to the binlog files, which is acceptable.fileInfo, err := binlogFileInfo.Info()if err != nil {- log.Warn("Failed to get file info.", zap.String("path", binlogFileInfo.Name()), zap.Error(err))+ slog.Warn("Failed to get file info.", slog.String("path", binlogFileInfo.Name()), log.BBError(err))continue}expireTime := fileInfo.ModTime().Add(time.Duration(retentionPeriodTs) * time.Second)if time.Now().After(expireTime) {binlogFilePath := path.Join(binlogDir, binlogFileInfo.Name())- log.Debug("Deleting expired local binlog file for MySQL instance.", zap.String("path", binlogFilePath))+ slog.Debug("Deleting expired local binlog file for MySQL instance.", slog.String("path", binlogFilePath))if err := os.Remove(binlogFilePath); err != nil {if !os.IsNotExist(err) {- log.Warn("Failed to remove an expired binlog file.", zap.String("path", binlogFilePath), zap.Error(err))+ slog.Warn("Failed to remove an expired binlog file.", slog.String("path", binlogFilePath), log.BBError(err))}continue}- log.Info("Deleted expired binlog file.", zap.String("path", binlogFilePath))+ slog.Info("Deleted expired binlog file.", slog.String("path", binlogFilePath))}}return nil@@ -237,7 +237,7 @@ func (r *Runner) purgeBackup(ctx context.Context, backup *store.BackupMessage) eif _, err := r.store.UpdateBackupV2(ctx, backupPatch); err != nil {return errors.Wrapf(err, "failed to update status for deleted backup %q for database with ID %d", backup.Name, backup.DatabaseUID)}- log.Debug("Archived expired backup record", zap.String("name", backup.Name), zap.Int("id", backup.UID))+ slog.Debug("Archived expired backup record", slog.String("name", backup.Name), slog.Int("id", backup.UID))switch backup.StorageBackend {case api.BackupStorageBackendLocal:@@ -245,13 +245,13 @@ func (r *Runner) purgeBackup(ctx context.Context, backup *store.BackupMessage) eif err := os.Remove(backupFilePath); err != nil {return errors.Wrapf(err, "failed to delete an expired backup file %q", backupFilePath)}- log.Debug(fmt.Sprintf("Deleted expired local backup file %s", backupFilePath))+ slog.Debug(fmt.Sprintf("Deleted expired local backup file %s", backupFilePath))case api.BackupStorageBackendS3:backupFilePath := getBackupRelativeFilePath(backup.DatabaseUID, backup.Name)if _, err := r.s3Client.DeleteObjects(ctx, backupFilePath); err != nil {return errors.Wrapf(err, "failed to delete backup file %s in the cloud storage", backupFilePath)}- log.Debug(fmt.Sprintf("Deleted expired backup file %s in the cloud storage", backupFilePath))+ slog.Debug(fmt.Sprintf("Deleted expired backup file %s in the cloud storage", backupFilePath))}return nil@@ -260,7 +260,7 @@ func (r *Runner) purgeBackup(ctx context.Context, backup *store.BackupMessage) efunc (r *Runner) downloadBinlogFiles(ctx context.Context) {instances, err := r.store.FindInstanceWithDatabaseBackupEnabled(ctx)if err != nil {- log.Error("Failed to retrieve MySQL instance list with at least one database backup enabled", zap.Error(err))+ slog.Error("Failed to retrieve MySQL instance list with at least one database backup enabled", log.BBError(err))return}@@ -288,21 +288,21 @@ func (r *Runner) downloadBinlogFilesForInstance(ctx context.Context, instance *sdriver, err := r.dbFactory.GetAdminDatabaseDriver(ctx, instance, nil /* database */)if err != nil {if common.ErrorCode(err) == common.DbConnectionFailure {- log.Debug("Cannot connect to instance", zap.String("instance", instance.ResourceID), zap.Error(err))+ slog.Debug("Cannot connect to instance", slog.String("instance", instance.ResourceID), log.BBError(err))return}- log.Error("Failed to get driver for MySQL instance when downloading binlog", zap.String("instance", instance.ResourceID), zap.Error(err))+ slog.Error("Failed to get driver for MySQL instance when downloading binlog", slog.String("instance", instance.ResourceID), log.BBError(err))return}defer driver.Close(ctx)mysqlDriver, ok := driver.(*mysql.Driver)if !ok {- log.Error("Failed to cast driver to mysql.Driver", zap.String("instance", instance.ResourceID))+ slog.Error("Failed to cast driver to mysql.Driver", slog.String("instance", instance.ResourceID))return}if err := mysqlDriver.FetchAllBinlogFiles(ctx, false /* downloadLatestBinlogFile */, r.s3Client); err != nil {- log.Error("Failed to download all binlog files for instance", zap.String("instance", instance.ResourceID), zap.Error(err))+ slog.Error("Failed to download all binlog files for instance", slog.String("instance", instance.ResourceID), log.BBError(err))return}}@@ -315,7 +315,7 @@ func (r *Runner) startAutoBackups(ctx context.Context) {DayOfWeek: int(t.Weekday()),})if err != nil {- log.Error("Failed to retrieve backup settings match", zap.Error(err))+ slog.Error("Failed to retrieve backup settings match", log.BBError(err))return}@@ -325,19 +325,19 @@ func (r *Runner) startAutoBackups(ctx context.Context) {}database, err := r.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: &backupSetting.DatabaseUID})if err != nil {- log.Error("Failed to get database", zap.Error(err))+ slog.Error("Failed to get database", log.BBError(err))return}project, err := r.store.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &database.ProjectID})if err != nil {- log.Error("Failed to get project", zap.Error(err))+ slog.Error("Failed to get project", log.BBError(err))}if project.Deleted {continue}instance, err := r.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &database.InstanceID})if err != nil {- log.Error("Failed to get instance", zap.Error(err))+ slog.Error("Failed to get instance", log.BBError(err))}if instance.Deleted {continue@@ -348,7 +348,7 @@ func (r *Runner) startAutoBackups(ctx context.Context) {}environment, err := r.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})if err != nil {- log.Error("Failed to get environment", zap.Error(err))+ slog.Error("Failed to get environment", log.BBError(err))}if environment.Deleted {continue@@ -359,7 +359,7 @@ func (r *Runner) startAutoBackups(ctx context.Context) {Name: &backupName,})if err != nil {- log.Error("Failed to find backup", zap.Error(err))+ slog.Error("Failed to find backup", log.BBError(err))continue}if len(backupList) > 0 {@@ -372,14 +372,14 @@ func (r *Runner) startAutoBackups(ctx context.Context) {r.stateCfg.RunningBackupDatabases.Delete(database.UID)r.backupWg.Done()}()- log.Debug("Schedule auto backup",- zap.String("database", database.DatabaseName),- zap.String("backup", backupName),+ slog.Debug("Schedule auto backup",+ slog.String("database", database.DatabaseName),+ slog.String("backup", backupName),)if _, err := r.ScheduleBackupTask(ctx, database, backupName, api.BackupTypeAutomatic, api.SystemBotID); err != nil {- log.Error("Failed to create automatic backup for database",- zap.Int("databaseID", database.UID),- zap.Error(err))+ slog.Error("Failed to create automatic backup for database",+ slog.Int("databaseID", database.UID),+ log.BBError(err))return}// Backup succeeded. POST hook URL.@@ -388,10 +388,10 @@ func (r *Runner) startAutoBackups(ctx context.Context) {}resp, err := http.PostForm(hookURL, nil)if err != nil {- log.Warn("Failed to POST hook URL",- zap.String("hookURL", hookURL),- zap.Int("databaseID", database.UID),- zap.Error(err))+ slog.Warn("Failed to POST hook URL",+ slog.String("hookURL", hookURL),+ slog.Int("databaseID", database.UID),+ log.BBError(err))}defer resp.Body.Close()}(database, backupName, backupSetting.HookURL)@@ -445,7 +445,7 @@ func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.Databas}, database.UID, creatorID)if err != nil {if common.ErrorCode(err) == common.Conflict {- log.Error("Backup already exists for the database", zap.String("backup", backupName), zap.String("database", database.DatabaseName))+ slog.Error("Backup already exists for the database", slog.String("backup", backupName), slog.String("database", database.DatabaseName))return nil, nil}return nil, errors.Wrapf(err, "failed to create backup %q", backupName)diff --git a/backend/runner/mail/slow_query_weekly_mail.go b/backend/runner/mail/slow_query_weekly_mail.goindex 1d2fcaef59..f936e2e8b5 100644--- a/backend/runner/mail/slow_query_weekly_mail.go+++ b/backend/runner/mail/slow_query_weekly_mail.go@@ -6,12 +6,12 @@ import ("context""embed""fmt"+ "log/slog""sort""strings""sync""time"- "go.uber.org/zap""google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common/log"@@ -63,14 +63,14 @@ func (s *SlowQueryWeeklyMailSender) Run(ctx context.Context, wg *sync.WaitGroup)ticker := time.NewTicker(1 * time.Hour)defer ticker.Stop()defer wg.Done()- log.Debug("Slow query weekly mail sender started")+ slog.Debug("Slow query weekly mail sender started")for {select {case <-ctx.Done():- log.Debug("Slow query weekly mail sender received context cancellation")+ slog.Debug("Slow query weekly mail sender received context cancellation")returncase <-ticker.C:- log.Debug("Slow query weekly mail sender received tick")+ slog.Debug("Slow query weekly mail sender received tick")now := time.Now()// Send email every Saturday in 00:00 ~ 00:59.if now.Weekday() == time.Saturday && now.Hour() == 0 {@@ -84,7 +84,7 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.Timename := api.SettingWorkspaceMailDeliverymailSetting, err := s.store.GetSettingV2(ctx, &store.FindSettingMessage{Name: &name})if err != nil {- log.Error("Failed to get mail setting", zap.Error(err))+ slog.Error("Failed to get mail setting", log.BBError(err))return}@@ -94,7 +94,7 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.Timevar storeValue storepb.SMTPMailDeliverySettingif err := protojson.Unmarshal([]byte(mailSetting.Value), &storeValue); err != nil {- log.Error("Failed to unmarshal setting value", zap.Error(err))+ slog.Error("Failed to unmarshal setting value", log.BBError(err))return}apiValue := convertStorepbToAPIMailDeliveryValue(&storeValue)@@ -103,13 +103,13 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.TimeworkspaceProfileSettingName := api.SettingWorkspaceProfilesetting, err := s.store.GetSettingV2(ctx, &store.FindSettingMessage{Name: &workspaceProfileSettingName})if err != nil {- log.Error("Failed to get workspace profile setting", zap.Error(err))+ slog.Error("Failed to get workspace profile setting", log.BBError(err))return}if setting != nil {settingValue := new(storepb.WorkspaceProfileSetting)if err := protojson.Unmarshal([]byte(setting.Value), settingValue); err != nil {- log.Error("Failed to unmarshal setting value", zap.Error(err))+ slog.Error("Failed to unmarshal setting value", log.BBError(err))return}if settingValue.ExternalUrl != "" {@@ -124,7 +124,7 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.TimeResourceType: &instanceResourceType,})if err != nil {- log.Error("Failed to list slow query policies", zap.Error(err))+ slog.Error("Failed to list slow query policies", log.BBError(err))return}@@ -132,7 +132,7 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.Timefor _, policy := range policies {payload, err := api.UnmarshalSlowQueryPolicy(policy.Payload)if err != nil {- log.Error("Failed to unmarshal slow query policy payload", zap.Error(err))+ slog.Error("Failed to unmarshal slow query policy payload", log.BBError(err))return}if payload.Active {@@ -144,12 +144,12 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.TimedbaRole := api.DBAusers, err := s.store.ListUsers(ctx, &store.FindUserMessage{Role: &dbaRole})if err != nil {- log.Error("Failed to list dba users", zap.Error(err))+ slog.Error("Failed to list dba users", log.BBError(err))} else {for _, user := range users {apiValue.SMTPTo = user.Emailif err := s.sendNeedConfigSlowQueryPolicyEmail(apiValue, consoleRedirectURL); err != nil {- log.Error("Failed to send need config slow query policy email", zap.String("user", user.Name), zap.String("email", user.Email), zap.Error(err))+ slog.Error("Failed to send need config slow query policy email", slog.String("user", user.Name), slog.String("email", user.Email), log.BBError(err))}}}@@ -157,12 +157,12 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.TimeownerRole := api.Ownerusers, err = s.store.ListUsers(ctx, &store.FindUserMessage{Role: &ownerRole})if err != nil {- log.Error("Failed to list owner users", zap.Error(err))+ slog.Error("Failed to list owner users", log.BBError(err))} else {for _, user := range users {apiValue.SMTPTo = user.Emailif err := s.sendNeedConfigSlowQueryPolicyEmail(apiValue, consoleRedirectURL); err != nil {- log.Error("Failed to send need config slow query policy email", zap.String("user", user.Name), zap.String("email", user.Email), zap.Error(err))+ slog.Error("Failed to send need config slow query policy email", slog.String("user", user.Name), slog.String("email", user.Email), log.BBError(err))}}}@@ -173,38 +173,38 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.TimedbaRole := api.DBAusers, err := s.store.ListUsers(ctx, &store.FindUserMessage{Role: &dbaRole})if err != nil {- log.Error("Failed to list dba users", zap.Error(err))+ slog.Error("Failed to list dba users", log.BBError(err))} else {for _, user := range users {apiValue.SMTPTo = user.Emailif err := send(apiValue, fmt.Sprintf("Database slow query weekly report %s", generateDateRange(now)), body); err != nil {- log.Error("Failed to send need config slow query policy email", zap.String("user", user.Name), zap.String("email", user.Email), zap.Error(err))+ slog.Error("Failed to send need config slow query policy email", slog.String("user", user.Name), slog.String("email", user.Email), log.BBError(err))}}}} else {- log.Error("Failed to generate weekly email for dba", zap.Error(err))+ slog.Error("Failed to generate weekly email for dba", log.BBError(err))}projects, err := s.store.ListProjectV2(ctx, &store.FindProjectMessage{})if err != nil {- log.Error("Failed to list projects", zap.Error(err))+ slog.Error("Failed to list projects", log.BBError(err))return}for _, project := range projects {body, err := s.generateWeeklyEmailForProject(ctx, project, activePolicies, now, consoleRedirectURL)if err != nil {- log.Error("Failed to generate weekly email for project", zap.Error(err))+ slog.Error("Failed to generate weekly email for project", log.BBError(err))continue}if len(body) == 0 {- log.Debug("No slow query found for project", zap.String("project", project.Title))+ slog.Debug("No slow query found for project", slog.String("project", project.Title))continue}projectPolicy, err := s.store.GetProjectPolicy(ctx, &store.GetProjectPolicyMessage{ProjectID: &project.ResourceID})if err != nil {- log.Error("Failed to get project policy", zap.Error(err))+ slog.Error("Failed to get project policy", log.BBError(err))continue}@@ -214,7 +214,7 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.TimeapiValue.SMTPTo = member.Emailsubject := fmt.Sprintf("%s database slow query weekly report %s", project.Title, generateDateRange(now))if err := send(apiValue, subject, body); err != nil {- log.Error("Failed to send need config slow query policy email", zap.String("user", member.Name), zap.String("email", member.Email), zap.Error(err))+ slog.Error("Failed to send need config slow query policy email", slog.String("user", member.Name), slog.String("email", member.Email), log.BBError(err))}}}@@ -271,7 +271,7 @@ func (s *SlowQueryWeeklyMailSender) generateWeeklyEmailForProject(ctx context.Cofor _, policy := range policies {instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &policy.ResourceUID})if err != nil {- log.Warn("Failed to get instance", zap.Error(err))+ slog.Warn("Failed to get instance", log.BBError(err))continue}instanceMap[instance.ResourceID] = instance@@ -404,7 +404,7 @@ func send(mailSetting *api.SettingWorkspaceMailDeliveryValue, subject string, boif err := client.SendMail(email); err != nil {return err}- log.Debug("Successfully sent need configure slow query policy email", zap.String("to", mailSetting.SMTPTo), zap.String("subject", subject))+ slog.Debug("Successfully sent need configure slow query policy email", slog.String("to", mailSetting.SMTPTo), slog.String("subject", subject))return nil}@@ -474,7 +474,7 @@ func (s *SlowQueryWeeklyMailSender) generateWeeklyEmailForDBA(ctx context.Contexfor _, policy := range policies {instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &policy.ResourceUID})if err != nil {- log.Warn("Failed to get instance", zap.Error(err))+ slog.Warn("Failed to get instance", log.BBError(err))continue}@@ -679,7 +679,7 @@ func (*SlowQueryWeeklyMailSender) sendNeedConfigSlowQueryPolicyEmail(mailSettingif err := client.SendMail(email); err != nil {return err}- log.Debug("Successfully sent need configure slow query policy email", zap.String("to", mailSetting.SMTPTo))+ slog.Debug("Successfully sent need configure slow query policy email", slog.String("to", mailSetting.SMTPTo))return nil}diff --git a/backend/runner/metricreport/reporter.go b/backend/runner/metricreport/reporter.goindex fe0db024eb..a74ef15236 100644--- a/backend/runner/metricreport/reporter.go+++ b/backend/runner/metricreport/reporter.go@@ -4,6 +4,7 @@ package metricreportimport ("context""fmt"+ "log/slog""sync""time"@@ -16,8 +17,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/metric""github.com/bytebase/bytebase/backend/plugin/metric/segment""github.com/bytebase/bytebase/backend/store"-- "go.uber.org/zap")const (@@ -79,7 +78,7 @@ func (m *Reporter) Run(ctx context.Context, wg *sync.WaitGroup) {defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Metrics reporter started and will run every %v", metricSchedulerInterval))+ slog.Debug(fmt.Sprintf("Metrics reporter started and will run every %v", metricSchedulerInterval))for {select {@@ -91,7 +90,7 @@ func (m *Reporter) Run(ctx context.Context, wg *sync.WaitGroup) {if !ok {err = errors.Errorf("%v", r)}- log.Error("Metrics reporter PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Metrics reporter PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()@@ -99,19 +98,19 @@ func (m *Reporter) Run(ctx context.Context, wg *sync.WaitGroup) {// identify will be triggered in every schedule loop so that we can update the latest workspace profile such as subscription plan.workspaceID, err := m.identify(ctx)if err != nil {- log.Error("failed to report identifier", zap.Error(err))+ slog.Error("failed to report identifier", log.BBError(err))return}for name, collector := range m.collectors {- log.Debug("Run metric collector", zap.String("collector", name))+ slog.Debug("Run metric collector", slog.String("collector", name))metricList, err := collector.Collect(ctx)if err != nil {- log.Error(+ slog.Error("Failed to collect metric",- zap.String("collector", name),- zap.Error(err),+ slog.String("collector", name),+ log.BBError(err),)continue}@@ -139,10 +138,10 @@ func (m *Reporter) Register(metricName metric.Name, collector metric.Collector)func (m *Reporter) reportMetric(id string, metric *metric.Metric) {if err := m.reporter.Report(id, metric); err != nil {- log.Error(+ slog.Error("Failed to report metric",- zap.String("metric", string(metric.Name)),- zap.Error(err),+ slog.String("metric", string(metric.Name)),+ log.BBError(err),)}}@@ -172,7 +171,7 @@ func (m *Reporter) identify(ctx context.Context) (string, error) {user, err := m.store.GetUserByID(ctx, api.PrincipalIDForFirstUser)if err != nil {- log.Debug("unable to get the first principal user", zap.Int("id", api.PrincipalIDForFirstUser), zap.Error(err))+ slog.Debug("unable to get the first principal user", slog.Int("id", api.PrincipalIDForFirstUser), log.BBError(err))}email := ""name := ""@@ -212,7 +211,7 @@ func (m *Reporter) identify(ctx context.Context) (string, error) {func (m *Reporter) Report(ctx context.Context, metric *metric.Metric) {workspaceID, err := m.store.GetWorkspaceID(ctx)if err != nil {- log.Error("failed to find the workspace id", zap.Error(err))+ slog.Error("failed to find the workspace id", log.BBError(err))return}m.reportMetric(workspaceID, metric)diff --git a/backend/runner/plancheck/executor.go b/backend/runner/plancheck/executor.goindex 1cef30e9e5..07625cb84f 100644--- a/backend/runner/plancheck/executor.go+++ b/backend/runner/plancheck/executor.go@@ -2,9 +2,9 @@ package plancheckimport ("context"+ "log/slog""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db"@@ -19,7 +19,7 @@ func runExecutorOnce(ctx context.Context, exec Executor, planCheckRun *store.Plaif !ok {panicErr = errors.Errorf("%v", r)}- log.Error("TaskExecutor PANIC RECOVER", zap.Error(panicErr), zap.Stack("panic-stack"))+ slog.Error("TaskExecutor PANIC RECOVER", log.BBError(panicErr), log.BBStack("panic-stack"))err = errors.Errorf("encounter internal error when executing check")}}()diff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.goindex 4d1009f94d..61a54d16f0 100644--- a/backend/runner/plancheck/scheduler.go+++ b/backend/runner/plancheck/scheduler.go@@ -4,11 +4,11 @@ package plancheckimport ("context""fmt"+ "log/slog""sync""time""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/state"@@ -45,7 +45,7 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(planCheckSchedulerInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Plan check scheduler started and will run every %v", planCheckSchedulerInterval))+ slog.Debug(fmt.Sprintf("Plan check scheduler started and will run every %v", planCheckSchedulerInterval))for {select {case <-ticker.C:@@ -74,7 +74,7 @@ func (s *Scheduler) runOnce(ctx context.Context) {if !ok {err = errors.Errorf("%v", r)}- log.Error("Plan check scheduler PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Plan check scheduler PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()@@ -84,7 +84,7 @@ func (s *Scheduler) runOnce(ctx context.Context) {},})if err != nil {- log.Error("failed to list running plan check runs", zap.Error(err))+ slog.Error("failed to list running plan check runs", log.BBError(err))return}@@ -96,7 +96,7 @@ func (s *Scheduler) runOnce(ctx context.Context) {func (s *Scheduler) runPlanCheckRun(ctx context.Context, planCheckRun *store.PlanCheckRunMessage) {executor, ok := s.executors[planCheckRun.Type]if !ok {- log.Error("Skip running plan check for unknown type", zap.Int("uid", planCheckRun.UID), zap.Int64("plan_uid", planCheckRun.PlanUID), zap.String("type", string(planCheckRun.Type)))+ slog.Error("Skip running plan check for unknown type", slog.Int("uid", planCheckRun.UID), slog.Int64("plan_uid", planCheckRun.PlanUID), slog.String("type", string(planCheckRun.Type)))return}if _, ok := s.stateCfg.RunningPlanChecks.Load(planCheckRun.UID); ok {@@ -140,7 +140,7 @@ func (s *Scheduler) markPlanCheckRunDone(ctx context.Context, planCheckRun *storresult,planCheckRun.UID,); err != nil {- log.Error("failed to mark plan check run failed", zap.Error(err))+ slog.Error("failed to mark plan check run failed", log.BBError(err))}}@@ -154,6 +154,6 @@ func (s *Scheduler) markPlanCheckRunFailed(ctx context.Context, planCheckRun *stresult,planCheckRun.UID,); err != nil {- log.Error("failed to mark plan check run failed", zap.Error(err))+ slog.Error("failed to mark plan check run failed", log.BBError(err))}}diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.goindex 10b23e70e8..072f24e68e 100644--- a/backend/runner/plancheck/statement_report_executor.go+++ b/backend/runner/plancheck/statement_report_executor.go@@ -4,13 +4,13 @@ import ("context""database/sql""fmt"+ "log/slog""strings"pgquery "github.com/pganalyze/pg_query_go/v4"tidbparser "github.com/pingcap/tidb/parser"tidbast "github.com/pingcap/tidb/parser/ast""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -363,7 +363,7 @@ func reportForOracle(databaseName string, schemaName string, statement string) (}resources, err := getChangedResourcesForOracle(databaseName, schemaName, stmt.Text)if err != nil {- log.Error("failed to extract changed resources", zap.String("statement", stmt.Text), zap.Error(err))+ slog.Error("failed to extract changed resources", slog.String("statement", stmt.Text), log.BBError(err))} else {changedResources = append(changedResources, resources...)}@@ -424,11 +424,11 @@ func reportForMySQL(ctx context.Context, sqlDB *sql.DB, dbType db.Type, database}root, _, err := p.Parse(stmt.Text, charset, collation)if err != nil {- log.Error("failed to parse statement", zap.String("statement", stmt.Text), zap.Error(err))+ slog.Error("failed to parse statement", slog.String("statement", stmt.Text), log.BBError(err))continue}if len(root) != 1 {- log.Error("failed to parse statement, expect to get one node from parser", zap.String("statement", stmt.Text), zap.Error(err))+ slog.Error("failed to parse statement, expect to get one node from parser", slog.String("statement", stmt.Text), log.BBError(err))continue}sqlType, resources := getStatementTypeFromTidbAstNode(strings.ToLower(databaseName), root[0])@@ -437,7 +437,7 @@ func reportForMySQL(ctx context.Context, sqlDB *sql.DB, dbType db.Type, databaseif dbType != db.TiDB {resources, err := getStatementChangedResourcesForMySQL(databaseName, stmt.Text)if err != nil {- log.Error("failed to get statement changed resources", zap.Error(err))+ slog.Error("failed to get statement changed resources", log.BBError(err))} else {changedResources = append(changedResources, resources...)}@@ -448,7 +448,7 @@ func reportForMySQL(ctx context.Context, sqlDB *sql.DB, dbType db.Type, databaseaffectedRows, err := getAffectedRowsForMysql(ctx, dbType, sqlDB, root[0])if err != nil {- log.Error("failed to get affected rows for mysql", zap.String("database", databaseName), zap.Error(err))+ slog.Error("failed to get affected rows for mysql", slog.String("database", databaseName), log.BBError(err))} else {totalAffectedRows += affectedRows}@@ -533,7 +533,7 @@ func reportForPostgres(ctx context.Context, sqlDB *sql.DB, database, statement sif sqlType == "COMMENT" {resources, err = postgresExtractResourcesFromCommentStatement(database, "public", stmt.Text())if err != nil {- log.Error("failed to extract resources from comment statement", zap.String("statement", stmt.Text()), zap.Error(err))+ slog.Error("failed to extract resources from comment statement", slog.String("statement", stmt.Text()), log.BBError(err))resources = nil}}@@ -542,7 +542,7 @@ func reportForPostgres(ctx context.Context, sqlDB *sql.DB, database, statement srowCount, err := getAffectedRowsForPostgres(ctx, sqlDB, stmt)if err != nil {- log.Error("failed to get affected rows for postgres", zap.String("database", database), zap.Error(err))+ slog.Error("failed to get affected rows for postgres", slog.String("database", database), log.BBError(err))} else {totalAffectedRows += rowCount}diff --git a/backend/runner/relay/runner.go b/backend/runner/relay/runner.goindex b33389b3ac..d8b7e1c9e4 100644--- a/backend/runner/relay/runner.go+++ b/backend/runner/relay/runner.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""strconv""strings""sync"@@ -12,7 +13,6 @@ import ("github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common/log"@@ -63,7 +63,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(relayRunnerInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Relay runner started and will run every %v", relayRunnerInterval))+ slog.Debug(fmt.Sprintf("Relay runner started and will run every %v", relayRunnerInterval))wg.Add(1)go r.listenIssueExternalApprovalRelayCancelChan(ctx, wg)@@ -97,7 +97,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {return errs}()if err != nil {- log.Error("relay runner: failed to check external approval", zap.Error(err))+ slog.Error("relay runner: failed to check external approval", log.BBError(err))}case <-ctx.Done():return@@ -174,7 +174,7 @@ func (r *Runner) cancelExternalApproval(ctx context.Context, issueUID int) {IssueUID: &issueUID,})if err != nil {- log.Error("failed to list external approvals", zap.Error(err))+ slog.Error("failed to list external approvals", log.BBError(err))return}if len(approvals) == 0 {@@ -185,27 +185,27 @@ func (r *Runner) cancelExternalApproval(ctx context.Context, issueUID int) {ID: approval.ID,RowStatus: api.Archived,}); err != nil {- log.Error("failed to archive external approval", zap.Error(err))+ slog.Error("failed to archive external approval", log.BBError(err))continue}payload := &api.ExternalApprovalPayloadRelay{}if err := json.Unmarshal([]byte(approval.Payload), payload); err != nil {- log.Error("failed to unmarshal external approval payload", zap.Error(err))+ slog.Error("failed to unmarshal external approval payload", log.BBError(err))continue}// don't wait for http requests, just fire and forgetnode, err := getExternalApprovalByID(ctx, r.store, payload.ExternalApprovalNodeID)if err != nil {- log.Error("failed to get external approval node", zap.Error(err))+ slog.Error("failed to get external approval node", log.BBError(err))continue}if node == nil {- log.Error("external approval node not found", zap.String("id", payload.ExternalApprovalNodeID))+ slog.Error("external approval node not found", slog.String("id", payload.ExternalApprovalNodeID))continue}go func() {if err := r.Client.UpdateApproval(node.Endpoint, payload.ID, &relayplugin.UpdatePayload{}); err != nil {- log.Error("failed to update external approval status", zap.String("endpoint", node.Endpoint), zap.String("id", payload.ID), zap.Error(err))+ slog.Error("failed to update external approval status", slog.String("endpoint", node.Endpoint), slog.String("id", payload.ID), log.BBError(err))}}()}@@ -316,7 +316,7 @@ func (r *Runner) approveExternalApprovalNode(ctx context.Context, issueUID int)return nil}(); err != nil {- log.Error("failed to create skipping steps activity after approving review", zap.Error(err))+ slog.Error("failed to create skipping steps activity after approving review", log.BBError(err))}if err := func() error {@@ -354,7 +354,7 @@ func (r *Runner) approveExternalApprovalNode(ctx context.Context, issueUID int)return nil}(); err != nil {- log.Error("failed to create approval step pending activity after creating review", zap.Error(err))+ slog.Error("failed to create approval step pending activity after creating review", log.BBError(err))}// Grant the privilege if the issue is approved.@@ -417,7 +417,7 @@ func (r *Runner) approveExternalApprovalNode(ctx context.Context, issueUID int)Level: api.ActivityInfo,Comment: fmt.Sprintf("Granted %s to %s (%s).", newUser.Name, newUser.Email, role),}, &activity.Metadata{}); err != nil {- log.Warn("Failed to create project activity", zap.Error(err))+ slog.Warn("Failed to create project activity", log.BBError(err))}}if issue.Type == api.IssueGrantRequest {@@ -437,7 +437,7 @@ func (r *Runner) approveExternalApprovalNode(ctx context.Context, issueUID int)}return nil}(); err != nil {- log.Debug("failed to update issue status to done if grant request issue is approved", zap.Error(err))+ slog.Debug("failed to update issue status to done if grant request issue is approved", log.BBError(err))}}@@ -522,7 +522,7 @@ func (r *Runner) rejectExternalApprovalNode(ctx context.Context, issueUID int) e}return nil}(); err != nil {- log.Error("failed to create activity after rejecting review", zap.Error(err))+ slog.Error("failed to create activity after rejecting review", log.BBError(err))}return nildiff --git a/backend/runner/rollbackrun/runner.go b/backend/runner/rollbackrun/runner.goindex ada3754d0e..985316d215 100644--- a/backend/runner/rollbackrun/runner.go+++ b/backend/runner/rollbackrun/runner.go@@ -7,11 +7,11 @@ import ("database/sql""encoding/json""fmt"+ "log/slog""sync""time""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -53,7 +53,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {case <-ticker.C:r.stateCfg.RollbackGenerate.Range(func(key, value any) bool {task := value.(*store.TaskMessage)- log.Debug(fmt.Sprintf("Generating rollback SQL for task %d", task.ID))+ slog.Debug(fmt.Sprintf("Generating rollback SQL for task %d", task.ID))ctx, cancel := context.WithCancel(ctx)r.stateCfg.RollbackCancel.Store(task.ID, cancel)r.generateRollbackSQL(ctx, task)@@ -77,11 +77,11 @@ func (r *Runner) retryGenerateRollbackSQL(ctx context.Context) {Payload: "(task.payload->>'rollbackEnabled')::BOOLEAN IS TRUE AND (task.payload->>'threadId'!='' OR task.payload->>'transactionId' != '') AND task.payload->>'rollbackSqlStatus'='PENDING'",})if err != nil {- log.Error("Failed to get running DML tasks", zap.Error(err))+ slog.Error("Failed to get running DML tasks", log.BBError(err))return}for _, task := range taskList {- log.Debug("retry generate rollback SQL for task", zap.Int("ID", task.ID), zap.String("name", task.Name))+ slog.Debug("retry generate rollback SQL for task", slog.Int("ID", task.ID), slog.String("name", task.Name))r.stateCfg.RollbackGenerate.Store(task.ID, task)}}@@ -93,28 +93,28 @@ func (r *Runner) generateRollbackSQL(ctx context.Context, task *store.TaskMessagif !ok {err = errors.Errorf("%v", r)}- log.Error("Rollback runner PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Rollback runner PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()payload := &api.TaskDatabaseDataUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- log.Error("Invalid database data update payload", zap.Error(err))+ slog.Error("Invalid database data update payload", log.BBError(err))return}instance, err := r.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})if err != nil {- log.Error("Failed to find instance", zap.Error(err))+ slog.Error("Failed to find instance", log.BBError(err))return}database, err := r.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: task.DatabaseID})if err != nil {- log.Error("Failed to find database", zap.Error(err))+ slog.Error("Failed to find database", log.BBError(err))return}project, err := r.store.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &database.ProjectID})if err != nil {- log.Error("Failed to find project", zap.Error(err))+ slog.Error("Failed to find project", log.BBError(err))return}@@ -133,7 +133,7 @@ func (r *Runner) generateOracleRollbackSQL(ctx context.Context, task *store.TaskstatementsBuffer, err := r.generateOracleRollbackSQLImpl(ctx, payload, instance)if err != nil {- log.Error("Failed to generate rollback SQL statement", zap.Error(err))+ slog.Error("Failed to generate rollback SQL statement", log.BBError(err))rollbackSQLStatus = api.RollbackSQLStatusFailedrollbackError = err.Error()} else {@@ -151,7 +151,7 @@ func (r *Runner) generateOracleRollbackSQL(ctx context.Context, task *store.TaskType: store.SheetForSQL,})if err != nil {- log.Error("failed to create database creation sheet", zap.Error(err))+ slog.Error("failed to create database creation sheet", log.BBError(err))return}@@ -163,10 +163,10 @@ func (r *Runner) generateOracleRollbackSQL(ctx context.Context, task *store.TaskRollbackError: &rollbackError,}if _, err := r.store.UpdateTaskV2(ctx, patch); err != nil {- log.Error("Failed to patch task with the Oracle payload", zap.Int("taskID", task.ID))+ slog.Error("Failed to patch task with the Oracle payload", slog.Int("taskID", task.ID))return}- log.Debug("Rollback SQL generation success", zap.Int("taskID", task.ID))+ slog.Debug("Rollback SQL generation success", slog.Int("taskID", task.ID))}func (r *Runner) generateOracleRollbackSQLImpl(ctx context.Context, payload *api.TaskDatabaseDataUpdatePayload, instance *store.InstanceMessage) (*bytes.Buffer, error) {@@ -220,7 +220,7 @@ func (r *Runner) generateMySQLRollbackSQL(ctx context.Context, task *store.TaskM} else if mysql.IsErrParseBinlogName(err) {rollbackError = "Failed to generate rollback SQL statement. Please check if binlog is enabled."} else {- log.Error("Failed to generate rollback SQL statement", zap.Error(err))+ slog.Error("Failed to generate rollback SQL statement", log.BBError(err))rollbackError = err.Error()}} else {@@ -238,7 +238,7 @@ func (r *Runner) generateMySQLRollbackSQL(ctx context.Context, task *store.TaskMType: store.SheetForSQL,})if err != nil {- log.Error("failed to create database creation sheet", zap.Error(err))+ slog.Error("failed to create database creation sheet", log.BBError(err))return}patch := &api.TaskPatch{@@ -249,10 +249,10 @@ func (r *Runner) generateMySQLRollbackSQL(ctx context.Context, task *store.TaskMRollbackError: &rollbackError,}if _, err := r.store.UpdateTaskV2(ctx, patch); err != nil {- log.Error("Failed to patch task with the MySQL thread ID", zap.Int("taskID", task.ID))+ slog.Error("Failed to patch task with the MySQL thread ID", slog.Int("taskID", task.ID))return}- log.Debug("Rollback SQL generation success", zap.Int("taskID", task.ID))+ slog.Debug("Rollback SQL generation success", slog.Int("taskID", task.ID))}func (r *Runner) generateMySQLRollbackSQLImpl(ctx context.Context, payload *api.TaskDatabaseDataUpdatePayload, binlogSizeLimit int, instance *store.InstanceMessage) (string, error) {diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.goindex d85f8a6eba..b2839ea519 100644--- a/backend/runner/schemasync/syncer.go+++ b/backend/runner/schemasync/syncer.go@@ -6,12 +6,12 @@ import ("context""encoding/json""fmt"+ "log/slog""sync""time""github.com/google/go-cmp/cmp""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/testing/protocmp""google.golang.org/protobuf/types/known/timestamppb"@@ -59,7 +59,7 @@ func (s *Syncer) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(schemaSyncInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Schema syncer started and will run every %v", schemaSyncInterval))+ slog.Debug(fmt.Sprintf("Schema syncer started and will run every %v", schemaSyncInterval))for {select {case <-ticker.C:@@ -80,12 +80,12 @@ func (s *Syncer) trySyncAll(ctx context.Context) {if !ok {err = errors.Errorf("%v", r)}- log.Error("Instance syncer PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Instance syncer PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()instances, err := s.store.ListInstancesV2(ctx, &store.FindInstanceMessage{})if err != nil {- log.Error("Failed to retrieve instances", zap.Error(err))+ slog.Error("Failed to retrieve instances", log.BBError(err))return}@@ -103,11 +103,11 @@ func (s *Syncer) trySyncAll(ctx context.Context) {continue}- log.Debug("Sync instance schema", zap.String("instance", instance.ResourceID))+ slog.Debug("Sync instance schema", slog.String("instance", instance.ResourceID))if err := s.SyncInstance(ctx, instance); err != nil {- log.Debug("Failed to sync instance",- zap.String("instance", instance.ResourceID),- zap.String("error", err.Error()))+ slog.Debug("Failed to sync instance",+ slog.String("instance", instance.ResourceID),+ slog.String("error", err.Error()))}}@@ -118,7 +118,7 @@ func (s *Syncer) trySyncAll(ctx context.Context) {databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{})if err != nil {- log.Error("Failed to retrieve databases", zap.Error(err))+ slog.Error("Failed to retrieve databases", log.BBError(err))return}for _, database := range databases {@@ -139,10 +139,10 @@ func (s *Syncer) trySyncAll(ctx context.Context) {continue}if err := s.SyncDatabaseSchema(ctx, database, false /* force */); err != nil {- log.Debug("Failed to sync database schema",- zap.String("instance", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err))+ slog.Debug("Failed to sync database schema",+ slog.String("instance", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err))}}}@@ -154,7 +154,7 @@ func (s *Syncer) syncAllDatabases(ctx context.Context, instance *store.InstanceMif !ok {err = errors.Errorf("%v", r)}- log.Error("Database syncer PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Database syncer PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()@@ -164,8 +164,8 @@ func (s *Syncer) syncAllDatabases(ctx context.Context, instance *store.InstanceM}databases, err := s.store.ListDatabases(ctx, find)if err != nil {- log.Debug("Failed to find databases to sync",- zap.String("error", err.Error()))+ slog.Debug("Failed to find databases to sync",+ slog.String("error", err.Error()))return}@@ -189,18 +189,18 @@ func (s *Syncer) syncAllDatabases(ctx context.Context, instance *store.InstanceM}for _, database := range databaseList {instanceID := database.InstanceID- log.Debug("Sync database schema",- zap.String("instance", instanceID),- zap.String("database", database.DatabaseName),- zap.Int64("lastSuccessfulSyncTs", database.SuccessfulSyncTimeTs),+ slog.Debug("Sync database schema",+ slog.String("instance", instanceID),+ slog.String("database", database.DatabaseName),+ slog.Int64("lastSuccessfulSyncTs", database.SuccessfulSyncTimeTs),)// If we fail to sync a particular database due to permission issue, we will continue to sync the rest of the databases.// We don't force dump database schema because it's rarely changed till the metadata is changed.if err := s.SyncDatabaseSchema(ctx, database, false /* force */); err != nil {- log.Debug("Failed to sync database schema",- zap.String("instance", instanceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err))+ slog.Debug("Failed to sync database schema",+ slog.String("instance", instanceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err))}}}(databaseList)@@ -390,11 +390,11 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.DatabasLimit: &limit,})if err != nil {- log.Error("Failed to check anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseSchemaDrift)),- zap.Error(err))+ slog.Error("Failed to check anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseSchemaDrift)),+ log.BBError(err))return nil}latestSchema := string(rawDump)@@ -407,11 +407,11 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databas}payload, err := json.Marshal(anomalyPayload)if err != nil {- log.Error("Failed to marshal anomaly payload",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseSchemaDrift)),- zap.Error(err))+ slog.Error("Failed to marshal anomaly payload",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseSchemaDrift)),+ log.BBError(err))} else {if _, err = s.store.UpsertActiveAnomalyV2(ctx, api.SystemBotID, &store.AnomalyMessage{InstanceID: instance.ResourceID,@@ -419,11 +419,11 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.DatabasType: api.AnomalyDatabaseSchemaDrift,Payload: string(payload),}); err != nil {- log.Error("Failed to create anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseSchemaDrift)),- zap.Error(err))+ slog.Error("Failed to create anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseSchemaDrift)),+ log.BBError(err))}}} else {@@ -432,11 +432,11 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.DatabasType: api.AnomalyDatabaseSchemaDrift,})if err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to close anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseSchemaDrift)),- zap.Error(err))+ slog.Error("Failed to close anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseSchemaDrift)),+ log.BBError(err))}}}diff --git a/backend/runner/slowquerysync/syncer.go b/backend/runner/slowquerysync/syncer.goindex 90f942becf..bd89eaae4c 100644--- a/backend/runner/slowquerysync/syncer.go+++ b/backend/runner/slowquerysync/syncer.go@@ -4,11 +4,11 @@ package slowquerysyncimport ("context""fmt"+ "log/slog""sync""time""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb""github.com/bytebase/bytebase/backend/common/log"@@ -52,17 +52,17 @@ func (s *Syncer) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(slowQuerySyncInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Slow query syncer started and will run every %s", slowQuerySyncInterval.String()))+ slog.Debug(fmt.Sprintf("Slow query syncer started and will run every %s", slowQuerySyncInterval.String()))for {select {case <-ctx.Done():- log.Debug("Slow query syncer received context cancellation")+ slog.Debug("Slow query syncer received context cancellation")returncase message := <-s.stateCfg.InstanceSlowQuerySyncChan:- log.Debug("Slow query syncer received instance slow query sync request", zap.String("instance", message.InstanceID), zap.String("project", message.ProjectID))+ slog.Debug("Slow query syncer received instance slow query sync request", slog.String("instance", message.InstanceID), slog.String("project", message.ProjectID))s.syncSlowQuery(ctx, message)case <-ticker.C:- log.Debug("Slow query syncer received tick")+ slog.Debug("Slow query syncer received tick")s.syncSlowQuery(ctx, nil)}}@@ -75,7 +75,7 @@ func (s *Syncer) syncSlowQuery(ctx context.Context, message *state.InstanceSlowQif !ok {err = errors.Errorf("%v", r)}- log.Error("slow query syncer PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("slow query syncer PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()@@ -87,7 +87,7 @@ func (s *Syncer) syncSlowQuery(ctx context.Context, message *state.InstanceSlowQ}instances, err := s.store.ListInstancesV2(ctx, find)if err != nil {- log.Error("Failed to list instances", zap.Error(err))+ slog.Error("Failed to list instances", log.BBError(err))return}@@ -100,9 +100,9 @@ func (s *Syncer) syncSlowQuery(ctx context.Context, message *state.InstanceSlowQgo func(instance *store.InstanceMessage) {defer instanceWG.Done()if err := s.syncInstanceSlowQuery(ctx, instance, project); err != nil {- log.Debug("Failed to sync instance slow query",- zap.String("instance", instance.ResourceID),- zap.Error(err))+ slog.Debug("Failed to sync instance slow query",+ slog.String("instance", instance.ResourceID),+ log.BBError(err))}}(instance)}@@ -165,11 +165,11 @@ func (s *Syncer) syncPostgreSQLSlowQuery(ctx context.Context, instance *store.Indefer driver.Close(ctx)return driver.CheckSlowQueryLogEnabled(ctx)}(); err != nil {- log.Warn("pg_stat_statements is not enabled",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.Int("databaseID", database.UID),- zap.Error(err))+ slog.Warn("pg_stat_statements is not enabled",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.Int("databaseID", database.UID),+ log.BBError(err))continue}@@ -212,11 +212,11 @@ func (s *Syncer) syncPostgreSQLSlowQuery(ctx context.Context, instance *store.InEndLogDate: &nextLogDate,})if err != nil {- log.Warn("Failed to list slow query logs",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.Int("databaseID", database.UID),- zap.Error(err))+ slog.Warn("Failed to list slow query logs",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.Int("databaseID", database.UID),+ log.BBError(err))logs = nil}@@ -232,11 +232,11 @@ func (s *Syncer) syncPostgreSQLSlowQuery(ctx context.Context, instance *store.InSlowLog: statistics,UpdaterID: api.SystemBotID,}); err != nil {- log.Warn("Failed to upsert slow query log",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.Int("databaseID", database.UID),- zap.Error(err))+ slog.Warn("Failed to upsert slow query log",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.Int("databaseID", database.UID),+ log.BBError(err))}}diff --git a/backend/runner/taskrun/database_backup_executor.go b/backend/runner/taskrun/database_backup_executor.goindex 6db9c050a2..7b4ef68f2c 100644--- a/backend/runner/taskrun/database_backup_executor.go+++ b/backend/runner/taskrun/database_backup_executor.go@@ -4,11 +4,11 @@ import ("context""encoding/json""fmt"+ "log/slog""os""path/filepath""github.com/pkg/errors"- "go.uber.org/zap""golang.org/x/sys/unix""github.com/bytebase/bytebase/backend/common/log"@@ -80,7 +80,7 @@ func (exec *DatabaseBackupExecutor) RunOnce(ctx context.Context, _ context.Contereturn true, nil, errors.Errorf("the available file system space %dMB is less than the minimal threshold %dMB", availableBytes/1024/1024, minAvailableFSBytes/1024/1024)}}- log.Debug("Start database backup.", zap.String("instance", instance.Title), zap.String("database", database.DatabaseName), zap.String("backup", backup.Name))+ slog.Debug("Start database backup.", slog.String("instance", instance.Title), slog.String("database", database.DatabaseName), slog.String("backup", backup.Name))backupPayload, backupErr := exec.backupDatabase(ctx, exec.dbFactory, exec.s3Client, exec.profile, instance, database, backup)backupStatus := string(api.BackupStatusDone)comment := ""@@ -88,7 +88,7 @@ func (exec *DatabaseBackupExecutor) RunOnce(ctx context.Context, _ context.ContebackupStatus = string(api.BackupStatusFailed)comment = backupErr.Error()if err := removeLocalBackupFile(exec.profile.DataDir, backup); err != nil {- log.Warn(err.Error())+ slog.Warn(err.Error())}}backupPatch := store.UpdateBackupMessage{@@ -169,7 +169,7 @@ func (*DatabaseBackupExecutor) backupDatabase(ctx context.Context, dbFactory *dbcase api.BackupStorageBackendLocal:return payload, nilcase api.BackupStorageBackendS3:- log.Debug("Uploading backup to s3 bucket.", zap.String("bucket", s3Client.GetBucket()), zap.String("path", backupFilePathLocal))+ slog.Debug("Uploading backup to s3 bucket.", slog.String("bucket", s3Client.GetBucket()), slog.String("path", backupFilePathLocal))bucketFileToUpload, err := os.Open(backupFilePathLocal)if err != nil {return "", errors.Wrapf(err, "failed to open backup file %q for uploading to s3 bucket", backupFilePathLocal)@@ -179,12 +179,12 @@ func (*DatabaseBackupExecutor) backupDatabase(ctx context.Context, dbFactory *dbif _, err := s3Client.UploadObject(ctx, backup.Path, bucketFileToUpload); err != nil {return "", errors.Wrapf(err, "failed to upload backup to AWS S3")}- log.Debug("Successfully uploaded backup to s3 bucket.")+ slog.Debug("Successfully uploaded backup to s3 bucket.")if err := os.Remove(backupFilePathLocal); err != nil {- log.Warn("Failed to remove the local backup file after uploading to s3 bucket.", zap.String("path", backupFilePathLocal), zap.Error(err))+ slog.Warn("Failed to remove the local backup file after uploading to s3 bucket.", slog.String("path", backupFilePathLocal), log.BBError(err))} else {- log.Debug("Successfully removed the local backup file after uploading to s3 bucket.", zap.String("path", backupFilePathLocal))+ slog.Debug("Successfully removed the local backup file after uploading to s3 bucket.", slog.String("path", backupFilePathLocal))}return payload, nildefault:diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.goindex a7d3d62d12..35a0b6e5d1 100644--- a/backend/runner/taskrun/database_create_executor.go+++ b/backend/runner/taskrun/database_create_executor.go@@ -5,12 +5,12 @@ import ("context""encoding/json""fmt"+ "log/slog""strconv""strings""time""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/config"@@ -88,10 +88,10 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, driverCtx conte}// Create database.- log.Debug("Start creating database...",- zap.String("instance", instance.Title),- zap.String("database", payload.DatabaseName),- zap.String("statement", statement),+ slog.Debug("Start creating database...",+ slog.String("instance", instance.Title),+ slog.String("database", payload.DatabaseName),+ slog.String("statement", statement),)// Upsert first because we need database id in instance change history.@@ -204,10 +204,10 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, driverCtx conte}if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),)}@@ -256,9 +256,9 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driif err != nil {// If somehow we unable to find the principal, we just emit the error since it's not// critical enough to fail the entire operation.- log.Error("Failed to fetch creator for composing the migration info",- zap.Int("task_id", task.ID),- zap.Error(err),+ slog.Error("Failed to fetch creator for composing the migration info",+ slog.Int("task_id", task.ID),+ log.BBError(err),)} else {mi.Creator = creator.Name@@ -267,16 +267,16 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driif err != nil {// If somehow we unable to find the issue, we just emit the error since it's not// critical enough to fail the entire operation.- log.Error("Failed to fetch containing issue for composing the migration info",- zap.Int("task_id", task.ID),- zap.Error(err),+ slog.Error("Failed to fetch containing issue for composing the migration info",+ slog.Int("task_id", task.ID),+ log.BBError(err),)}if issue == nil {err := errors.Errorf("failed to fetch containing issue for composing the migration info, issue not found with pipeline ID %v", task.PipelineID)- log.Error(err.Error(),- zap.Int("task_id", task.ID),- zap.Error(err),+ slog.Error(err.Error(),+ slog.Int("task_id", task.ID),+ log.BBError(err),)} else {mi.IssueID = strconv.Itoa(issue.UID)diff --git a/backend/runner/taskrun/default_executor.go b/backend/runner/taskrun/default_executor.goindex b79273fd8c..e1a5f96df9 100644--- a/backend/runner/taskrun/default_executor.go+++ b/backend/runner/taskrun/default_executor.go@@ -3,10 +3,8 @@ package taskrunimport ("context""fmt"+ "log/slog"- "go.uber.org/zap"-- "github.com/bytebase/bytebase/backend/common/log"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store")@@ -22,7 +20,7 @@ type DefaultExecutor struct {// RunOnce will run the default task executor once.func (*DefaultExecutor) RunOnce(_ context.Context, _ context.Context, task *store.TaskMessage) (terminated bool, result *api.TaskRunResultPayload, err error) {- log.Info("Run default task type", zap.String("task", task.Name))+ slog.Info("Run default task type", slog.String("task", task.Name))return true, &api.TaskRunResultPayload{Detail: fmt.Sprintf("No-op task %s", task.Name)}, nil}diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 2796d559bb..917ce14a2c 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -5,6 +5,7 @@ import ("database/sql""encoding/json""fmt"+ "log/slog""path/filepath""sort""strconv"@@ -12,7 +13,6 @@ import ("github.com/gosimple/slug""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -54,7 +54,7 @@ func RunExecutorOnce(ctx context.Context, driverCtx context.Context, exec Executif !ok {panicErr = errors.Errorf("%v", r)}- log.Error("TaskExecutor PANIC RECOVER", zap.Error(panicErr), zap.Stack("panic-stack"))+ slog.Error("TaskExecutor PANIC RECOVER", log.BBError(panicErr), log.BBStack("panic-stack"))terminated = trueresult = nilerr = errors.Errorf("encounter internal error when executing task")@@ -143,7 +143,7 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile config.Pissue, err := stores.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})if err != nil {- log.Error("failed to find containing issue", zap.Error(err))+ slog.Error("failed to find containing issue", log.BBError(err))}if issue != nil {// Concat issue title and task name as the migration description so that user can see@@ -158,9 +158,9 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile config.Pif err != nil {// If somehow we unable to find the principal, we just emit the error since it's not// critical enough to fail the entire operation.- log.Error("Failed to fetch creator for composing the migration info",- zap.Int("task_id", task.ID),- zap.Error(err),+ slog.Error("Failed to fetch creator for composing the migration info",+ slog.Int("task_id", task.ID),+ log.BBError(err),)} else {mi.Creator = creator.Name@@ -199,12 +199,12 @@ func executeMigration(ctx context.Context, driverCtx context.Context, stores *stdefer driver.Close(ctx)statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)- log.Debug("Start migration...",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("source", string(mi.Source)),- zap.String("type", string(mi.Type)),- zap.String("statement", statementRecord),+ slog.Debug("Start migration...",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("source", string(mi.Source)),+ slog.String("type", string(mi.Type)),+ slog.String("statement", statementRecord),)var migrationID string@@ -272,13 +272,13 @@ func getSetOracleTransactionIDFunc(ctx context.Context, task *store.TaskMessage,return func(tx *sql.Tx) error {payload := &api.TaskDatabaseDataUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- log.Error("failed to unmarshal task payload", zap.Int("TaskId", task.ID), zap.Error(err))+ slog.Error("failed to unmarshal task payload", slog.Int("TaskId", task.ID), log.BBError(err))return nil}// Get oracle current transaction id;transactionID, err := tx.QueryContext(ctx, "SELECT RAWTOHEX(tx.xid) FROM v$transaction tx JOIN v$session s ON tx.ses_addr = s.saddr")if err != nil {- log.Error("failed to transaction id in task", zap.Int("TaskId", task.ID), zap.Error(err))+ slog.Error("failed to transaction id in task", slog.Int("TaskId", task.ID), log.BBError(err))return nil}defer transactionID.Close()@@ -286,7 +286,7 @@ func getSetOracleTransactionIDFunc(ctx context.Context, task *store.TaskMessage,for transactionID.Next() {err := transactionID.Scan(&txID)if err != nil {- log.Error("failed to the Oracle transaction id in task", zap.Int("TaskId", task.ID), zap.Error(err))+ slog.Error("failed to the Oracle transaction id in task", slog.Int("TaskId", task.ID), log.BBError(err))return nil}}@@ -296,7 +296,7 @@ func getSetOracleTransactionIDFunc(ctx context.Context, task *store.TaskMessage,payload.TransactionID = txIDupdatedPayload, err := json.Marshal(payload)if err != nil {- log.Error("failed to unmarshal task payload", zap.Int("TaskId", task.ID), zap.Error(err), zap.Any("payload", updatedPayload))+ slog.Error("failed to unmarshal task payload", slog.Int("TaskId", task.ID), log.BBError(err), slog.Any("payload", updatedPayload))return nil}updatedPayloadString := string(updatedPayload)@@ -306,7 +306,7 @@ func getSetOracleTransactionIDFunc(ctx context.Context, task *store.TaskMessage,Payload: &updatedPayloadString,}if _, err = store.UpdateTaskV2(ctx, patch); err != nil {- log.Error("failed to update task with new payload", zap.Any("TaskPatch", patch), zap.Error(err))+ slog.Error("failed to update task with new payload", slog.Any("TaskPatch", patch), log.BBError(err))return nil}return nil@@ -330,7 +330,7 @@ func setThreadIDAndStartBinlogCoordinate(ctx context.Context, conn *sql.Conn, tareturn nil, errors.Wrap(err, "failed to get the binlog info before executing the migration transaction")}if (binlogInfo == api.BinlogInfo{}) {- log.Warn("binlog is not enabled", zap.Int("task", task.ID))+ slog.Warn("binlog is not enabled", slog.Int("task", task.ID))return task, nil}payload.BinlogFileStart = binlogInfo.FileName@@ -365,7 +365,7 @@ func setMigrationIDAndEndBinlogCoordinate(ctx context.Context, conn *sql.Conn, treturn nil, errors.Wrap(err, "failed to get the binlog info before executing the migration transaction")}if (binlogInfo == api.BinlogInfo{}) {- log.Warn("binlog is not enabled", zap.Int("task", task.ID))+ slog.Warn("binlog is not enabled", slog.Int("task", task.ID))return task, nil}payload.BinlogFileEnd = binlogInfo.FileName@@ -404,11 +404,11 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *acissue, err := stores.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})if err != nil {- log.Error("failed to find containing issue", zap.Error(err))+ slog.Error("failed to find containing issue", log.BBError(err))}if err != nil {// If somehow we cannot find the issue, emit the error since it's not fatal.- log.Error("failed to find containing issue", zap.Error(err))+ slog.Error("failed to find containing issue", log.BBError(err))}repo, err := stores.GetRepositoryV2(ctx, &store.FindRepositoryMessage{ProjectResourceID: &project.ResourceID,@@ -432,10 +432,10 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *acreturn true, nil, err}- log.Debug("Post migration...",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("writeback_branch", writebackBranch),+ slog.Debug("Post migration...",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("writeback_branch", writebackBranch),)if writebackBranch != "" {@@ -486,11 +486,11 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *acCommitID: commitID,})if err != nil {- log.Error("Failed to marshal file commit activity after writing back the latest schema",- zap.Int("task_id", task.ID),- zap.String("repository", repo.WebURL),- zap.String("file_path", latestSchemaFile),- zap.Error(err),+ slog.Error("Failed to marshal file commit activity after writing back the latest schema",+ slog.Int("task_id", task.ID),+ slog.String("repository", repo.WebURL),+ slog.String("file_path", latestSchemaFile),+ log.BBError(err),)}@@ -507,11 +507,11 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac}if _, err := activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{}); err != nil {- log.Error("Failed to create file commit activity after writing back the latest schema",- zap.Int("task_id", task.ID),- zap.String("repository", repo.WebURL),- zap.String("file_path", latestSchemaFile),- zap.Error(err),+ slog.Error("Failed to create file commit activity after writing back the latest schema",+ slog.Int("task_id", task.ID),+ slog.String("repository", repo.WebURL),+ slog.String("file_path", latestSchemaFile),+ log.BBError(err),)}}@@ -522,11 +522,11 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *acDatabaseUID: task.DatabaseID,Type: api.AnomalyDatabaseSchemaDrift,}); err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to archive anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseSchemaDrift)),- zap.Error(err))+ slog.Error("Failed to archive anomaly",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),+ slog.String("type", string(api.AnomalyDatabaseSchemaDrift)),+ log.BBError(err))}detail := fmt.Sprintf("Applied migration version %s to database %q.", mi.Version, database.DatabaseName)@@ -565,7 +565,7 @@ func isWriteBack(ctx context.Context, stores *store.Store, license enterpriseAPI}if err := license.IsFeatureEnabledForInstance(api.FeatureVCSSchemaWriteBack, instance); err != nil {- log.Debug(err.Error(), zap.String("instance", instance.ResourceID))+ slog.Debug(err.Error(), slog.String("instance", instance.ResourceID))return "", nil}@@ -702,8 +702,8 @@ func writeBackLatestSchema(AuthorEmail: vcsPlugin.BytebaseAuthorEmail,}if createSchemaFile {- log.Debug("Create latest schema file",- zap.String("schema_file", latestSchemaFile),+ slog.Debug("Create latest schema file",+ slog.String("schema_file", latestSchemaFile),)err := vcsPlugin.Get(vcs2.Type, vcsPlugin.ProviderConfig{}).CreateFile(@@ -724,8 +724,8 @@ func writeBackLatestSchema(return "", errors.Wrapf(err, "failed to create file after applying migration %s to %q", mi.Version, mi.Database)}} else {- log.Debug("Update latest schema file",- zap.String("schema_file", latestSchemaFile),+ slog.Debug("Update latest schema file",+ slog.String("schema_file", latestSchemaFile),)schemaFileCommit.LastCommitID = schemaFileMeta.LastCommitIDdiff --git a/backend/runner/taskrun/pitr_cutover_executor.go b/backend/runner/taskrun/pitr_cutover_executor.goindex d88d4a60d2..b43bf7bc2d 100644--- a/backend/runner/taskrun/pitr_cutover_executor.go+++ b/backend/runner/taskrun/pitr_cutover_executor.go@@ -5,12 +5,12 @@ import ("database/sql""encoding/json""fmt"+ "log/slog""strconv""time""github.com/gosimple/slug""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -52,10 +52,10 @@ type PITRCutoverExecutor struct {// RunOnce will run the PITR cutover task executor once.// TODO: support cancellation.func (exec *PITRCutoverExecutor) RunOnce(ctx context.Context, _ context.Context, task *store.TaskMessage) (terminated bool, result *api.TaskRunResultPayload, err error) {- log.Info("Run PITR cutover task", zap.String("task", task.Name))+ slog.Info("Run PITR cutover task", slog.String("task", task.Name))issue, err := exec.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})if err != nil {- log.Error("failed to fetch containing issue doing pitr cutover task", zap.Error(err))+ slog.Error("failed to fetch containing issue doing pitr cutover task", log.BBError(err))return true, nil, err}if issue == nil {@@ -84,7 +84,7 @@ func (exec *PITRCutoverExecutor) RunOnce(ctx context.Context, _ context.Context,TaskName: task.Name,})if err != nil {- log.Error("failed to marshal activity", zap.Error(err))+ slog.Error("failed to marshal activity", log.BBError(err))return terminated, result, nil}@@ -97,7 +97,7 @@ func (exec *PITRCutoverExecutor) RunOnce(ctx context.Context, _ context.Context,Comment: fmt.Sprintf("Restore database %s in instance %s successfully.", database.DatabaseName, instance.Title),}if _, err = exec.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{Issue: issue}); err != nil {- log.Error("cannot create an pitr activity", zap.Error(err))+ slog.Error("cannot create an pitr activity", log.BBError(err))}return terminated, result, nil@@ -132,7 +132,7 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbf// RestorePITR will create the pitr database.// Since it's ephemeral and will be renamed to the original database soon, we will reuse the original// database's migration history, and append a new BRANCH migration.- log.Debug("Appending new migration history record")+ slog.Debug("Appending new migration history record")m := &db.MigrationInfo{InstanceID: &task.InstanceID,ReleaseVersion: profile.Version,@@ -157,7 +157,7 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbfdefer driver.Close(ctx)if _, _, err := utils.ExecuteMigrationDefault(ctx, ctx, exec.store, driver, m, "" /* pitr cutover */, nil, db.ExecuteOptions{}); err != nil {- log.Error("Failed to add migration history record", zap.Error(err))+ slog.Error("Failed to add migration history record", log.BBError(err))return true, nil, errors.Wrap(err, "failed to add migration history record")}@@ -169,10 +169,10 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbf// Sync database schema after restore is completed.if err := schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),)}@@ -197,7 +197,7 @@ func (exec *PITRCutoverExecutor) doCutover(ctx context.Context, instance *store.if retry == maxRetry {return errors.Wrapf(err, "failed to do cutover for PostgreSQL after retried for %d times", maxRetry)}- log.Debug("Failed to do cutover for PostgreSQL. Retry later.", zap.Error(err))+ slog.Debug("Failed to do cutover for PostgreSQL. Retry later.", log.BBError(err))} else {return nil}@@ -227,13 +227,13 @@ func (exec *PITRCutoverExecutor) pitrCutoverMySQL(ctx context.Context, instancereturn err}defer conn.Close()- log.Debug("Swapping the original and PITR database", zap.String("originalDatabase", databaseName))+ slog.Debug("Swapping the original and PITR database", slog.String("originalDatabase", databaseName))pitrDatabaseName, pitrOldDatabaseName, err := mysql.SwapPITRDatabase(ctx, conn, databaseName, issue.CreatedTime.Unix())if err != nil {- log.Error("Failed to swap the original and PITR database", zap.String("originalDatabase", databaseName), zap.String("pitrDatabase", pitrDatabaseName), zap.Error(err))+ slog.Error("Failed to swap the original and PITR database", slog.String("originalDatabase", databaseName), slog.String("pitrDatabase", pitrDatabaseName), log.BBError(err))return errors.Wrap(err, "failed to swap the original and PITR database")}- log.Debug("Finished swapping the original and PITR database", zap.String("originalDatabase", databaseName), zap.String("pitrDatabase", pitrDatabaseName), zap.String("oldDatabase", pitrOldDatabaseName))+ slog.Debug("Finished swapping the original and PITR database", slog.String("originalDatabase", databaseName), slog.String("pitrDatabase", pitrDatabaseName), slog.String("oldDatabase", pitrOldDatabaseName))return nil}@@ -262,7 +262,7 @@ func (exec *PITRCutoverExecutor) pitrCutoverPostgres(ctx context.Context, instanif _, err := db.ExecContext(ctx, fmt.Sprintf("ALTER DATABASE %s RENAME TO %s;", databaseName, pitrOldDatabaseName)); err != nil {return errors.Wrapf(err, "failed to rename database %q to %q", databaseName, pitrOldDatabaseName)}- log.Debug("Successfully renamed database", zap.String("from", databaseName), zap.String("to", pitrOldDatabaseName))+ slog.Debug("Successfully renamed database", slog.String("from", databaseName), slog.String("to", pitrOldDatabaseName))}// The _pitr database may not exist.@@ -284,7 +284,7 @@ func (exec *PITRCutoverExecutor) pitrCutoverPostgres(ctx context.Context, instanif _, err := db.ExecContext(ctx, fmt.Sprintf("ALTER DATABASE %s RENAME TO %s;", pitrDatabaseName, databaseName)); err != nil {return errors.Wrapf(err, "failed to rename database %q to %q", pitrDatabaseName, databaseName)}- log.Debug("Successfully renamed database", zap.String("from", pitrDatabaseName), zap.String("to", databaseName))+ slog.Debug("Successfully renamed database", slog.String("from", pitrDatabaseName), slog.String("to", databaseName))}return nildiff --git a/backend/runner/taskrun/pitr_restore_executor.go b/backend/runner/taskrun/pitr_restore_executor.goindex e13d0098b1..ae14c717e3 100644--- a/backend/runner/taskrun/pitr_restore_executor.go+++ b/backend/runner/taskrun/pitr_restore_executor.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "log/slog""os""path""path/filepath"@@ -11,7 +12,6 @@ import ("time""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -55,7 +55,7 @@ type PITRRestoreExecutor struct {// RunOnce will run the PITR restore task executor once.// TODO: support cancellation.func (exec *PITRRestoreExecutor) RunOnce(ctx context.Context, _ context.Context, task *store.TaskMessage) (terminated bool, result *api.TaskRunResultPayload, err error) {- log.Info("Run PITR restore task", zap.String("task", task.Name))+ slog.Info("Run PITR restore task", slog.String("task", task.Name))payload := api.TaskDatabasePITRRestorePayload{}if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {return true, nil, errors.Wrapf(err, "invalid PITR restore payload: %s", task.Payload)@@ -132,12 +132,12 @@ func (exec *PITRRestoreExecutor) doBackupRestore(ctx context.Context, stores *stif targetDatabase == nil {return nil, errors.Wrapf(err, "target database %q not found in instance %q", *payload.DatabaseName, instance.Title)}- log.Debug("Start database restore from backup...",- zap.String("source_instance", sourceDatabase.InstanceID),- zap.String("source_database", sourceDatabase.DatabaseName),- zap.String("target_instance", targetInstance.ResourceID),- zap.String("target_database", targetDatabase.DatabaseName),- zap.String("backup", backup.Name),+ slog.Debug("Start database restore from backup...",+ slog.String("source_instance", sourceDatabase.InstanceID),+ slog.String("source_database", sourceDatabase.DatabaseName),+ slog.String("target_instance", targetInstance.ResourceID),+ slog.String("target_database", targetDatabase.DatabaseName),+ slog.String("backup", backup.Name),)// Restore the database to the target database.@@ -165,10 +165,10 @@ func (exec *PITRRestoreExecutor) doBackupRestore(ctx context.Context, stores *st// Sync database schema after restore is completed.if err := schemaSyncer.SyncDatabaseSchema(ctx, targetDatabase, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", targetDatabase.InstanceID),- zap.String("databaseName", targetDatabase.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", targetDatabase.InstanceID),+ slog.String("databaseName", targetDatabase.DatabaseName),+ log.BBError(err),)}@@ -222,34 +222,34 @@ func (exec *PITRRestoreExecutor) doPITRRestore(ctx context.Context, dbFactory *dif err != nil {return nil, err}- log.Debug("Found backup list", zap.Array("backups", store.ZapBackupArray(backupList)))+ slog.Debug("Found backup list", "backups", store.SLogBackupArray(backupList))mysqlSourceDriver, sourceOk := sourceDriver.(*mysql.Driver)mysqlTargetDriver, targetOk := targetDriver.(*mysql.Driver)if (!sourceOk) || (!targetOk) {- log.Error("Failed to cast driver to mysql.Driver")+ slog.Error("Failed to cast driver to mysql.Driver")return nil, errors.Errorf("[internal] cast driver to mysql.Driver failed")}- log.Debug("Downloading all binlog files")+ slog.Debug("Downloading all binlog files")if err := mysqlSourceDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */, s3Client); err != nil {return nil, err}targetTs := *payload.PointInTimeTs- log.Debug("Getting latest backup before or equal to targetTs", zap.Int64("targetTs", targetTs))+ slog.Debug("Getting latest backup before or equal to targetTs", slog.Int64("targetTs", targetTs))backup, targetBinlogInfo, err := mysqlSourceDriver.GetLatestBackupBeforeOrEqualTs(ctx, backupList, targetTs, s3Client)if err != nil {targetTsHuman := time.Unix(targetTs, 0).Format(time.RFC822)- log.Error("Failed to get backup before or equal to time",- zap.Int64("targetTs", targetTs),- zap.String("targetTsHuman", targetTsHuman),- zap.Error(err))+ slog.Error("Failed to get backup before or equal to time",+ slog.Int64("targetTs", targetTs),+ slog.String("targetTsHuman", targetTsHuman),+ log.BBError(err))return nil, errors.Wrapf(err, "failed to get latest backup before or equal to %s", targetTsHuman)}startBinlogInfo := backup.Payload.BinlogInfobinlogDir := common.GetBinlogAbsDir(profile.DataDir, instance.UID)- log.Debug("Got latest backup before or equal to targetTs", zap.String("backup", backup.Name))+ slog.Debug("Got latest backup before or equal to targetTs", slog.String("backup", backup.Name))backupAbsPathLocal := backuprun.GetBackupAbsFilePath(profile.DataDir, backup.DatabaseUID, backup.Name)if backup.StorageBackend == api.BackupStorageBackendS3 {@@ -264,7 +264,7 @@ func (exec *PITRRestoreExecutor) doPITRRestore(ctx context.Context, dbFactory *ddefer func() {for _, binlogPath := range replayBinlogPathList {if err := os.Remove(binlogPath); err != nil {- log.Warn("Failed to remove downloaded local binlog file after PITR", zap.String("path", binlogPath))+ slog.Warn("Failed to remove downloaded local binlog file after PITR", slog.String("path", binlogPath))}}}()@@ -275,11 +275,11 @@ func (exec *PITRRestoreExecutor) doPITRRestore(ctx context.Context, dbFactory *dreturn nil, errors.Wrapf(err, "failed to open backup file %q", backupAbsPathLocal)}defer backupFile.Close()- log.Debug("Successfully opened backup file", zap.String("filename", backupAbsPathLocal))+ slog.Debug("Successfully opened backup file", slog.String("filename", backupAbsPathLocal))- log.Debug("Start creating and restoring PITR database",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),+ slog.Debug("Start creating and restoring PITR database",+ slog.String("instance", instance.ResourceID),+ slog.String("database", database.DatabaseName),)if err := exec.updateProgress(ctx, mysqlTargetDriver, task.ID, backupFile, startBinlogInfo, *targetBinlogInfo, binlogDir); err != nil {@@ -289,33 +289,33 @@ func (exec *PITRRestoreExecutor) doPITRRestore(ctx context.Context, dbFactory *dif payload.DatabaseName != nil {// case 1: PITR to a new database.if err := mysqlTargetDriver.RestoreBackupToDatabase(ctx, backupFile, *payload.DatabaseName); err != nil {- log.Error("failed to restore full backup in the new database",- zap.Int("issueID", issue.UID),- zap.String("databaseName", *payload.DatabaseName),- zap.Error(err))+ slog.Error("failed to restore full backup in the new database",+ slog.Int("issueID", issue.UID),+ slog.String("databaseName", *payload.DatabaseName),+ log.BBError(err))return nil, errors.Wrap(err, "failed to restore full backup in the new database")}if err := mysqlTargetDriver.ReplayBinlogToDatabase(ctx, database.DatabaseName, *payload.DatabaseName, startBinlogInfo, *targetBinlogInfo, targetTs, mysqlSourceDriver.GetBinlogDir()); err != nil {- log.Error("failed to perform a PITR restore in the new database",- zap.Int("issueID", issue.UID),- zap.String("databaseName", *payload.DatabaseName),- zap.Error(err))+ slog.Error("failed to perform a PITR restore in the new database",+ slog.Int("issueID", issue.UID),+ slog.String("databaseName", *payload.DatabaseName),+ log.BBError(err))return nil, errors.Wrap(err, "failed to perform a PITR restore in the new database")}} else {// case 2: in-place PITR.if err := mysqlTargetDriver.RestoreBackupToPITRDatabase(ctx, backupFile, database.DatabaseName, issue.CreatedTime.Unix()); err != nil {- log.Error("failed to restore full backup in the PITR database",- zap.Int("issueID", issue.UID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err))+ slog.Error("failed to restore full backup in the PITR database",+ slog.Int("issueID", issue.UID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err))return nil, errors.Wrap(err, "failed to perform a backup restore in the PITR database")}if err := mysqlTargetDriver.ReplayBinlogToPITRDatabase(ctx, database.DatabaseName, startBinlogInfo, *targetBinlogInfo, issue.CreatedTime.Unix(), targetTs); err != nil {- log.Error("failed to perform a PITR restore in the PITR database",- zap.Int("issueID", issue.UID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err))+ slog.Error("failed to perform a PITR restore in the PITR database",+ slog.Int("issueID", issue.UID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err))return nil, errors.Wrap(err, "failed to replay binlog in the PITR database")}}@@ -324,7 +324,7 @@ func (exec *PITRRestoreExecutor) doPITRRestore(ctx context.Context, dbFactory *dif payload.DatabaseName != nil {targetDatabaseName = *payload.DatabaseName}- log.Info("PITR restore success", zap.String("target database", targetDatabaseName))+ slog.Info("PITR restore success", slog.String("target database", targetDatabaseName))return &api.TaskRunResultPayload{Detail: fmt.Sprintf("PITR restore success for target database %q", targetDatabaseName),}, nil@@ -380,7 +380,7 @@ func (*PITRRestoreExecutor) doRestoreInPlacePostgres(ctx context.Context, storespgDriver, ok := driver.(*pg.Driver)if !ok {- log.Error("Failed to cast driver to pg.Driver")+ slog.Error("Failed to cast driver to pg.Driver")return nil, errors.Errorf("[internal] cast driver to pg.Driver failed")}originalOwner, err := pgDriver.GetCurrentDatabaseOwner()@@ -492,7 +492,7 @@ func (*PITRRestoreExecutor) restoreDatabase(ctx context.Context, dbFactory *dbfa}func downloadBackupFileFromCloud(ctx context.Context, s3Client *bbs3.Client, backupPath, backupAbsPathLocal string) error {- log.Debug("Downloading backup file from s3 bucket.", zap.String("path", backupPath))+ slog.Debug("Downloading backup file from s3 bucket.", slog.String("path", backupPath))backupFileDownload, err := os.Create(backupAbsPathLocal)if err != nil {return errors.Wrapf(err, "failed to create local backup file %q for downloading from s3 bucket", backupAbsPathLocal)@@ -501,7 +501,7 @@ func downloadBackupFileFromCloud(ctx context.Context, s3Client *bbs3.Client, bacif _, err := s3Client.DownloadObject(ctx, backupPath, backupFileDownload); err != nil {return errors.Wrapf(err, "failed to download backup file %q from s3 bucket", backupPath)}- log.Debug("Successfully downloaded backup file from s3 bucket.")+ slog.Debug("Successfully downloaded backup file from s3 bucket.")return nil}diff --git a/backend/runner/taskrun/schedulerv2.go b/backend/runner/taskrun/schedulerv2.goindex a8cdc26ebf..cd947e97c8 100644--- a/backend/runner/taskrun/schedulerv2.go+++ b/backend/runner/taskrun/schedulerv2.go@@ -4,11 +4,11 @@ import ("context""encoding/json""fmt"+ "log/slog""sync""time""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common"@@ -61,7 +61,7 @@ func (s *SchedulerV2) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(taskSchedulerInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Task scheduler V2 started and will run every %v", taskSchedulerInterval))+ slog.Debug(fmt.Sprintf("Task scheduler V2 started and will run every %v", taskSchedulerInterval))for {select {case <-ticker.C:@@ -79,20 +79,20 @@ func (s *SchedulerV2) runOnce(ctx context.Context) {if !ok {err = errors.Errorf("%v", r)}- log.Error("Task scheduler V2 PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Task scheduler V2 PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()if err := s.scheduleAutoRolloutTasks(ctx); err != nil {- log.Error("failed to schedule auto rollout tasks", zap.Error(err))+ slog.Error("failed to schedule auto rollout tasks", log.BBError(err))}if err := s.schedulePendingTaskRuns(ctx); err != nil {- log.Error("failed to schedule pending task runs", zap.Error(err))+ slog.Error("failed to schedule pending task runs", log.BBError(err))}if err := s.scheduleRunningTaskRuns(ctx); err != nil {- log.Error("failed to schedule running task runs", zap.Error(err))+ slog.Error("failed to schedule running task runs", log.BBError(err))}}@@ -103,7 +103,7 @@ func (s *SchedulerV2) scheduleAutoRolloutTasks(ctx context.Context) error {}for _, taskID := range taskIDs {if err := s.scheduleAutoRolloutTask(ctx, taskID); err != nil {- log.Error("failed to schedule auto rollout task", zap.Error(err))+ slog.Error("failed to schedule auto rollout task", log.BBError(err))}}return nil@@ -221,7 +221,7 @@ func (s *SchedulerV2) scheduleAutoRolloutTask(ctx context.Context, taskUID int)}if err := s.activityManager.BatchCreateActivitiesForRunTasks(ctx, []*store.TaskMessage{task}, issue, "", api.SystemBotID); err != nil {- log.Error("failed to create activities for running tasks", zap.Error(err))+ slog.Error("failed to create activities for running tasks", log.BBError(err))}return nil@@ -236,7 +236,7 @@ func (s *SchedulerV2) schedulePendingTaskRuns(ctx context.Context) error {}for _, taskRun := range taskRuns {if err := s.schedulePendingTaskRun(ctx, taskRun); err != nil {- log.Error("failed to schedule pending task run", zap.Error(err))+ slog.Error("failed to schedule pending task run", log.BBError(err))}}@@ -296,7 +296,7 @@ func (s *SchedulerV2) scheduleRunningTaskRuns(ctx context.Context) error {for _, taskRun := range taskRuns {task, err := s.store.GetTaskV2ByID(ctx, taskRun.TaskUID)if err != nil {- log.Error("failed to get task", zap.Int("task id", taskRun.TaskUID), zap.Error(err))+ slog.Error("failed to get task", slog.Int("task id", taskRun.TaskUID), log.BBError(err))continue}if task.DatabaseID == nil {@@ -316,7 +316,7 @@ func (s *SchedulerV2) scheduleRunningTaskRuns(ctx context.Context) error {}task, err := s.store.GetTaskV2ByID(ctx, taskRun.TaskUID)if err != nil {- log.Error("failed to get task", zap.Int("task id", taskRun.TaskUID), zap.Error(err))+ slog.Error("failed to get task", slog.Int("task id", taskRun.TaskUID), log.BBError(err))continue}if task.DatabaseID != nil && minTaskIDForDatabase[*task.DatabaseID] != task.ID {@@ -331,10 +331,10 @@ func (s *SchedulerV2) scheduleRunningTaskRuns(ctx context.Context) error {}executor, ok := s.executorMap[task.Type]if !ok {- log.Error("Skip running task with unknown type",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.String("type", string(task.Type)),+ slog.Error("Skip running task with unknown type",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ slog.String("type", string(task.Type)),)continue}@@ -368,21 +368,21 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRundone, result, err := RunExecutorOnce(ctx, driverCtx, executor, task)if !done && err != nil {- log.Debug("Encountered transient error running task, will retry",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.String("type", string(task.Type)),- zap.Error(err),+ slog.Debug("Encountered transient error running task, will retry",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ slog.String("type", string(task.Type)),+ log.BBError(err),)return}if done && err != nil && errors.Is(err, context.Canceled) {- log.Warn("task run is canceled",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.String("type", string(task.Type)),- zap.Error(err),+ slog.Warn("task run is canceled",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ slog.String("type", string(task.Type)),+ log.BBError(err),)resultBytes, marshalErr := protojson.Marshal(&storepb.TaskRunResult{Detail: "The task run is canceled",@@ -390,10 +390,10 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRunVersion: "",})if marshalErr != nil {- log.Error("Failed to marshal task run result",- zap.Int("task_id", task.ID),- zap.String("type", string(task.Type)),- zap.Error(marshalErr),+ slog.Error("Failed to marshal task run result",+ slog.Int("task_id", task.ID),+ slog.String("type", string(task.Type)),+ log.BBError(marshalErr),)return}@@ -408,10 +408,10 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRun}if _, err := s.store.UpdateTaskRunStatus(ctx, taskRunStatusPatch); err != nil {- log.Error("Failed to mark task as CANCELED",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.Error(err),+ slog.Error("Failed to mark task as CANCELED",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ log.BBError(err),)return}@@ -419,11 +419,11 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRun}if done && err != nil {- log.Warn("task run failed",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.String("type", string(task.Type)),- zap.Error(err),+ slog.Warn("task run failed",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ slog.String("type", string(task.Type)),+ log.BBError(err),)resultBytes, marshalErr := protojson.Marshal(&storepb.TaskRunResult{@@ -432,10 +432,10 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRunVersion: "",})if marshalErr != nil {- log.Error("Failed to marshal task run result",- zap.Int("task_id", task.ID),- zap.String("type", string(task.Type)),- zap.Error(marshalErr),+ slog.Error("Failed to marshal task run result",+ slog.Int("task_id", task.ID),+ slog.String("type", string(task.Type)),+ log.BBError(marshalErr),)return}@@ -450,10 +450,10 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRun}if _, err := s.store.UpdateTaskRunStatus(ctx, taskRunStatusPatch); err != nil {- log.Error("Failed to mark task as FAILED",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.Error(err),+ slog.Error("Failed to mark task as FAILED",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ log.BBError(err),)return}@@ -468,10 +468,10 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRunVersion: result.Version,})if marshalErr != nil {- log.Error("Failed to marshal task run result",- zap.Int("task_id", task.ID),- zap.String("type", string(task.Type)),- zap.Error(marshalErr),+ slog.Error("Failed to marshal task run result",+ slog.Int("task_id", task.ID),+ slog.String("type", string(task.Type)),+ log.BBError(marshalErr),)return}@@ -485,10 +485,10 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRunResult: &result,}if _, err := s.store.UpdateTaskRunStatus(ctx, taskRunStatusPatch); err != nil {- log.Error("Failed to mark task as DONE",- zap.Int("id", task.ID),- zap.String("name", task.Name),- zap.Error(err),+ slog.Error("Failed to mark task as DONE",+ slog.Int("id", task.ID),+ slog.String("name", task.Name),+ log.BBError(err),)return}@@ -505,10 +505,10 @@ func (s *SchedulerV2) ListenTaskSkippedOrDone(ctx context.Context) {if !ok {err = errors.Errorf("%v", r)}- log.Error("ListenTaskSkippedOrDone PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("ListenTaskSkippedOrDone PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))}}()- log.Info("TaskSkippedOrDoneListener started")+ slog.Info("TaskSkippedOrDoneListener started")stageDoneConfirmed := map[int]bool{}for {@@ -597,7 +597,7 @@ func (s *SchedulerV2) ListenTaskSkippedOrDone(ctx context.Context) {}return nil}(); err != nil {- log.Error("failed to create ActivityPipelineStageStatusUpdate activity", zap.Error(err))+ slog.Error("failed to create ActivityPipelineStageStatusUpdate activity", log.BBError(err))}if pipelineDone {@@ -633,12 +633,12 @@ func (s *SchedulerV2) ListenTaskSkippedOrDone(ctx context.Context) {}return nil}(); err != nil {- log.Error("failed to update issue status", zap.Error(err))+ slog.Error("failed to update issue status", log.BBError(err))}}return nil}(); err != nil {- log.Error("failed to handle task skipped or done", zap.Error(err))+ slog.Error("failed to handle task skipped or done", log.BBError(err))}case <-ctx.Done():return@@ -683,7 +683,7 @@ func (s *SchedulerV2) createActivityForTaskRunStatusUpdate(ctx context.Context,return nil}(); err != nil {- log.Error("failed to create activity for task run status update", zap.Error(err))+ slog.Error("failed to create activity for task run status update", log.BBError(err))}}diff --git a/backend/runner/taskrun/schema_baseline_executor.go b/backend/runner/taskrun/schema_baseline_executor.goindex f5532d0a89..a2d3246336 100644--- a/backend/runner/taskrun/schema_baseline_executor.go+++ b/backend/runner/taskrun/schema_baseline_executor.go@@ -3,9 +3,9 @@ package taskrunimport ("context""encoding/json"+ "log/slog""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/activity"@@ -61,10 +61,10 @@ func (exec *SchemaBaselineExecutor) RunOnce(ctx context.Context, driverCtx conteterminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Baseline, "" /* statement */, payload.SchemaVersion, nil /* sheetID */)if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),)}diff --git a/backend/runner/taskrun/schema_update_executor.go b/backend/runner/taskrun/schema_update_executor.goindex 58ec9517fa..3b0065f6e4 100644--- a/backend/runner/taskrun/schema_update_executor.go+++ b/backend/runner/taskrun/schema_update_executor.go@@ -3,9 +3,9 @@ package taskrunimport ("context""encoding/json"+ "log/slog""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/activity"@@ -66,10 +66,10 @@ func (exec *SchemaUpdateExecutor) RunOnce(ctx context.Context, driverCtx contextterminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Migrate, statement, payload.SchemaVersion, &payload.SheetID)if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),)}diff --git a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go b/backend/runner/taskrun/schema_update_ghost_cutover_executor.goindex 604ad13657..98b788472c 100644--- a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go+++ b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go@@ -3,6 +3,7 @@ package taskrunimport ("context""encoding/json"+ "log/slog""os""strings""sync/atomic"@@ -10,7 +11,6 @@ import ("github.com/github/gh-ost/go/base""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -100,10 +100,10 @@ func (e *SchemaUpdateGhostCutoverExecutor) RunOnce(ctx context.Context, _ contex// not using the rendered statement here because we want to avoid leaking the rendered statementterminated, result, err := cutover(ctx, e.store, e.dbFactory, e.activityManager, e.license, e.profile, task, statement, payload.SheetID, payload.SchemaVersion, postponeFilename, sharedGhost.migrationContext, sharedGhost.errCh)if err := e.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),)}diff --git a/backend/runner/taskrun/schema_update_ghost_sync_executor.go b/backend/runner/taskrun/schema_update_ghost_sync_executor.goindex 2f53b04977..82e04379a8 100644--- a/backend/runner/taskrun/schema_update_ghost_sync_executor.go+++ b/backend/runner/taskrun/schema_update_ghost_sync_executor.go@@ -3,6 +3,7 @@ package taskrunimport ("context""encoding/json"+ "log/slog""strings""sync/atomic""time"@@ -10,7 +11,6 @@ import ("github.com/github/gh-ost/go/base""github.com/github/gh-ost/go/logic""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -143,7 +143,7 @@ func (exec *SchemaUpdateGhostSyncExecutor) runGhostMigration(ctx context.Contextgo func() {if err := migrator.Migrate(); err != nil {- log.Error("failed to run gh-ost migration", zap.Error(err))+ slog.Error("failed to run gh-ost migration", log.BBError(err))migrationError <- errreturn}diff --git a/backend/runner/taskrun/schema_update_sdl_executor.go b/backend/runner/taskrun/schema_update_sdl_executor.goindex 2898205826..a67d5de172 100644--- a/backend/runner/taskrun/schema_update_sdl_executor.go+++ b/backend/runner/taskrun/schema_update_sdl_executor.go@@ -3,9 +3,9 @@ package taskrunimport ("context""encoding/json"+ "log/slog""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/activity"@@ -77,10 +77,10 @@ func (exec *SchemaUpdateSDLExecutor) RunOnce(ctx context.Context, driverCtx contterminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.MigrateSDL, ddl, payload.SchemaVersion, &payload.SheetID)if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {- log.Error("failed to sync database schema",- zap.String("instanceName", instance.ResourceID),- zap.String("databaseName", database.DatabaseName),- zap.Error(err),+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),)}diff --git a/backend/server/recover.go b/backend/server/recover.goindex 5b02bc588f..866b9125c4 100644--- a/backend/server/recover.go+++ b/backend/server/recover.go@@ -1,9 +1,10 @@package serverimport (+ "log/slog"+"github.com/labstack/echo/v4""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log")@@ -16,7 +17,7 @@ func recoverMiddleware(next echo.HandlerFunc) echo.HandlerFunc {if !ok {err = errors.Errorf("%v", r)}- log.Error("Middleware PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ slog.Error("Middleware PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))c.Error(err)}diff --git a/backend/server/server.go b/backend/server/server.goindex f3b106a215..089134da83 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""net""net/http""runtime"@@ -31,7 +32,6 @@ import (scas "github.com/qiangmzsx/string-adapter/v2"echoSwagger "github.com/swaggo/echo-swagger""github.com/tmc/grpc-websocket-proxy/wsproxy"- "go.uber.org/zap""google.golang.org/grpc""google.golang.org/grpc/codes""google.golang.org/grpc/credentials/insecure"@@ -245,18 +245,18 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {}// Display config- log.Info("-----Config BEGIN-----")- log.Info(fmt.Sprintf("mode=%s", profile.Mode))- log.Info(fmt.Sprintf("dataDir=%s", profile.DataDir))- log.Info(fmt.Sprintf("resourceDir=%s", profile.ResourceDir))- log.Info(fmt.Sprintf("readonly=%t", profile.Readonly))- log.Info(fmt.Sprintf("debug=%t", profile.Debug))- log.Info(fmt.Sprintf("demoName=%s", profile.DemoName))- log.Info(fmt.Sprintf("backupStorageBackend=%s", profile.BackupStorageBackend))- log.Info(fmt.Sprintf("backupBucket=%s", profile.BackupBucket))- log.Info(fmt.Sprintf("backupRegion=%s", profile.BackupRegion))- log.Info(fmt.Sprintf("backupCredentialFile=%s", profile.BackupCredentialFile))- log.Info("-----Config END-------")+ slog.Info("-----Config BEGIN-----")+ slog.Info(fmt.Sprintf("mode=%s", profile.Mode))+ slog.Info(fmt.Sprintf("dataDir=%s", profile.DataDir))+ slog.Info(fmt.Sprintf("resourceDir=%s", profile.ResourceDir))+ slog.Info(fmt.Sprintf("readonly=%t", profile.Readonly))+ slog.Info(fmt.Sprintf("debug=%t", profile.Debug))+ slog.Info(fmt.Sprintf("demoName=%s", profile.DemoName))+ slog.Info(fmt.Sprintf("backupStorageBackend=%s", profile.BackupStorageBackend))+ slog.Info(fmt.Sprintf("backupBucket=%s", profile.BackupBucket))+ slog.Info(fmt.Sprintf("backupRegion=%s", profile.BackupRegion))+ slog.Info(fmt.Sprintf("backupCredentialFile=%s", profile.BackupCredentialFile))+ slog.Info("-----Config END-------")serverStarted := falsedefer func() {@@ -287,30 +287,30 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {// Start a Postgres sample server. This is used for onboarding users without requiring them to// configure an external instance.if profile.SampleDatabasePort != 0 {- log.Info("-----Sample Postgres Instance BEGIN-----")+ slog.Info("-----Sample Postgres Instance BEGIN-----")sampleDataDir := common.GetPostgresSampleDataDir(profile.DataDir, "test")- log.Info(fmt.Sprintf("Start test sample database sampleDatabasePort=%d sampleDataDir=%s", profile.SampleDatabasePort, sampleDataDir))+ slog.Info(fmt.Sprintf("Start test sample database sampleDatabasePort=%d sampleDataDir=%s", profile.SampleDatabasePort, sampleDataDir))if err := postgres.StartSampleInstance(ctx, s.pgBinDir, sampleDataDir, profile.SampleDatabasePort, profile.Mode); err != nil {return nil, err}sampleDataDir = common.GetPostgresSampleDataDir(profile.DataDir, "prod")- log.Info(fmt.Sprintf("Start prod sample database sampleDatabasePort=%d sampleDataDir=%s", profile.SampleDatabasePort+1, sampleDataDir))+ slog.Info(fmt.Sprintf("Start prod sample database sampleDatabasePort=%d sampleDataDir=%s", profile.SampleDatabasePort+1, sampleDataDir))if err := postgres.StartSampleInstance(ctx, s.pgBinDir, sampleDataDir, profile.SampleDatabasePort+1, profile.Mode); err != nil {return nil, err}- log.Info("-----Sample Postgres Instance END-----")+ slog.Info("-----Sample Postgres Instance END-----")}// New MetadataDB instance.if profile.UseEmbedDB() {pgDataDir := common.GetPostgresDataDir(profile.DataDir, profile.DemoName)- log.Info("-----Embedded Postgres BEGIN-----")- log.Info(fmt.Sprintf("Start embedded Postgres datastorePort=%d pgDataDir=%s", profile.DatastorePort, pgDataDir))+ slog.Info("-----Embedded Postgres BEGIN-----")+ slog.Info(fmt.Sprintf("Start embedded Postgres datastorePort=%d pgDataDir=%s", profile.DatastorePort, pgDataDir))if err := postgres.InitDB(s.pgBinDir, pgDataDir, profile.PgUser); err != nil {return nil, err}s.metaDB = store.NewMetadataDBWithEmbedPg(profile.PgUser, pgDataDir, s.pgBinDir, profile.DemoName, profile.Mode)- log.Info("-----Embedded Postgres END-----")+ slog.Info("-----Embedded Postgres END-----")} else {s.metaDB = store.NewMetadataDBWithExternalPg(profile.PgURL, s.pgBinDir, profile.DemoName, profile.Mode)}@@ -327,7 +327,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {}storeInstance := store.New(storeDB)if profile.Readonly {- log.Info("Database is opened in readonly mode. Skip migration and demo data setup.")+ slog.Info("Database is opened in readonly mode. Skip migration and demo data setup.")} else {metadataVersion, err := migrator.MigrateSchema(ctx, storeDB, !profile.UseEmbedDB(), s.pgBinDir, profile.DemoName, profile.Version, profile.Mode)if err != nil {@@ -346,7 +346,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.store = storeInstanceif err := s.store.BackfillIssueTsVector(ctx); err != nil {- log.Warn("failed to backfill issue ts vector", zap.Error(err))+ slog.Warn("failed to backfill issue ts vector", log.BBError(err))}s.licenseService, err = enterpriseService.NewLicenseService(profile.Mode, storeInstance)@@ -506,7 +506,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {// Middleware//- // API logger middleware.+ // API slogger middleware.e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{Skipper: func(c echo.Context) bool {if s.profile.Mode == common.ReleaseModeProd && !s.profile.Debug {@@ -561,7 +561,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {stack := make([]byte, maxStacksize)stack = stack[:runtime.Stack(stack, true)]// keep a multiline stack- log.Error("v1 server panic error", zap.Error(errors.Errorf("error: %v\n%s", p, stack)))+ slog.Error("v1 server panic error", log.BBError(errors.Errorf("error: %v\n%s", p, stack)))return status.Errorf(codes.Unknown, "error: %v", p)}recoveryUnaryInterceptor := recovery.UnaryServerInterceptor(recovery.WithRecoveryHandler(onPanic))@@ -778,7 +778,7 @@ func (s *Server) getInitSetting(ctx context.Context, datastore *store.Store) (*wif _, _, err := datastore.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{Name: api.SettingBrandingLogo,Value: "",- Description: "The branding logo image in base64 string format.",+ Description: "The branding slogo image in base64 string format.",}, api.SystemBotID); err != nil {return nil, err}@@ -989,7 +989,7 @@ func (s *Server) Run(ctx context.Context, port int) error {}go func() {if err := s.grpcServer.Serve(listen); err != nil {- log.Error("grpc server listen error", zap.Error(err))+ slog.Error("grpc server listen error", log.BBError(err))}}()return s.e.Start(fmt.Sprintf(":%d", port))@@ -997,8 +997,8 @@ func (s *Server) Run(ctx context.Context, port int) error {// Shutdown will shut down the server.func (s *Server) Shutdown(ctx context.Context) error {- log.Info("Stopping Bytebase...")- log.Info("Stopping web server...")+ slog.Info("Stopping Bytebase...")+ slog.Info("Stopping web server...")// Close the metric reporterif s.MetricReporter != nil {@@ -1048,10 +1048,10 @@ func (s *Server) Shutdown(ctx context.Context) error {// Shutdown postgres sample instance.if s.profile.SampleDatabasePort != 0 {if err := postgres.Stop(s.pgBinDir, common.GetPostgresSampleDataDir(s.profile.DataDir, "test")); err != nil {- log.Error("Failed to stop test postgres sample instance", zap.Error(err))+ slog.Error("Failed to stop test postgres sample instance", log.BBError(err))}if err := postgres.Stop(s.pgBinDir, common.GetPostgresSampleDataDir(s.profile.DataDir, "prod")); err != nil {- log.Error("Failed to stop prod postgres sample instance", zap.Error(err))+ slog.Error("Failed to stop prod postgres sample instance", log.BBError(err))}}@@ -1059,7 +1059,7 @@ func (s *Server) Shutdown(ctx context.Context) error {if s.metaDB != nil {s.metaDB.Close()}- log.Info("Bytebase stopped properly")+ slog.Info("Bytebase stopped properly")return nil}diff --git a/backend/server/server_frontend_not_embed.go b/backend/server/server_frontend_not_embed.goindex 49607e5e58..57b14f3efc 100644--- a/backend/server/server_frontend_not_embed.go+++ b/backend/server/server_frontend_not_embed.go@@ -4,15 +4,14 @@package serverimport (+ "log/slog""net/http""github.com/labstack/echo/v4"-- "github.com/bytebase/bytebase/backend/common/log")func embedFrontend(e *echo.Echo) {- log.Info("Skip embedding frontend, build with 'embed_frontend' tag if you want embedded frontend.")+ slog.Info("Skip embedding frontend, build with 'embed_frontend' tag if you want embedded frontend.")e.GET("/*", func(c echo.Context) error {return c.HTML(http.StatusOK, "This Bytebase build does not bundle frontend and backend together.")diff --git a/backend/server/webhook.go b/backend/server/webhook.goindex 262c1c2f7d..7ce65793b5 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -9,6 +9,7 @@ import ("encoding/json""fmt""io"+ "log/slog""net/http""net/mail""net/url"@@ -22,7 +23,6 @@ import ("github.com/labstack/echo/v4""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/encoding/protojson""gopkg.in/yaml.v3"@@ -84,10 +84,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {for _, commit := range pushEvent.CommitList {commitList = append(commitList, commit.ID)}- log.Debug("all commits are created by Bytebase",- zap.String("repoURL", pushEvent.Project.WebURL),- zap.String("repoName", pushEvent.Project.FullPath),- zap.String("commits", strings.Join(commitList, ", ")),+ slog.Debug("all commits are created by Bytebase",+ slog.String("repoURL", pushEvent.Project.WebURL),+ slog.String("repoName", pushEvent.Project.FullPath),+ slog.String("commits", strings.Join(commitList, ", ")),)return c.String(http.StatusOK, "OK")}@@ -105,7 +105,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return err}if len(repositoryList) == 0 {- log.Debug("Empty handle repo list. Ignore this push event.")+ slog.Debug("Empty handle repo list. Ignore this push event.")return c.String(http.StatusOK, "OK")}@@ -152,10 +152,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {for _, commit := range pushEvent.Commits {commitList = append(commitList, commit.ID)}- log.Debug("all commits are created by Bytebase",- zap.String("repoURL", pushEvent.Repository.HTMLURL),- zap.String("repoName", pushEvent.Repository.FullName),- zap.String("commits", strings.Join(commitList, ", ")),+ slog.Debug("all commits are created by Bytebase",+ slog.String("repoURL", pushEvent.Repository.HTMLURL),+ slog.String("repoName", pushEvent.Repository.FullName),+ slog.String("commits", strings.Join(commitList, ", ")),)return c.String(http.StatusOK, "OK")}@@ -177,7 +177,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return err}if len(repositoryList) == 0 {- log.Debug("Empty handle repo list. Ignore this push event.")+ slog.Debug("Empty handle repo list. Ignore this push event.")return c.String(http.StatusOK, "OK")}@@ -220,10 +220,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {commitList = append(commitList, commit.Hash)}}- log.Debug("all commits are created by Bytebase",- zap.String("repoURL", pushEvent.Repository.Links.HTML.Href),- zap.String("repoName", pushEvent.Repository.FullName),- zap.String("commits", strings.Join(commitList, ", ")),+ slog.Debug("all commits are created by Bytebase",+ slog.String("repoURL", pushEvent.Repository.Links.HTML.Href),+ slog.String("repoName", pushEvent.Repository.FullName),+ slog.String("commits", strings.Join(commitList, ", ")),)continue}@@ -237,7 +237,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return err}if len(repositoryList) == 0 {- log.Debug("Empty handle repo list. Ignore this push event.")+ slog.Debug("Empty handle repo list. Ignore this push event.")continue}repo := repositoryList[0]@@ -383,7 +383,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to filter repository").SetInternal(err)}if len(repositoryList) == 0 {- log.Debug("Empty handle repo list. Ignore this push event.")+ slog.Debug("Empty handle repo list. Ignore this push event.")return c.String(http.StatusOK, "No repository matched")}@@ -456,11 +456,11 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {for _, commit := range pushEvent.Resource.Commits {commitIDs = append(commitIDs, commit.CommitID)}- log.Debug("all commits are created by Bytebase",- zap.String("repoURL", pushEvent.Resource.Repository.URL),- zap.String("repoID", repositoryID),- zap.String("repoName", pushEvent.Resource.Repository.Name),- zap.String("commits", strings.Join(commitIDs, ", ")),+ slog.Debug("all commits are created by Bytebase",+ slog.String("repoURL", pushEvent.Resource.Repository.URL),+ slog.String("repoID", repositoryID),+ slog.String("repoName", pushEvent.Resource.Repository.Name),+ slog.String("commits", strings.Join(commitIDs, ", ")),)return c.String(http.StatusOK, "OK")}@@ -505,7 +505,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {if len(backfillCommits) == 1 && len(backfillCommits[0].AddedList) == 1 && strings.HasSuffix(backfillCommits[0].AddedList[0], azure.SQLReviewPipelineFilePath) {// Setup SQL review pipeline and policy.if err := azure.EnableSQLReviewCI(ctx, oauthContext, repositoryList[0].repository.ExternalID, repositoryList[0].repository.BranchFilter, repositoryList[0].repository.WebhookSecretToken); err != nil {- log.Error("failed to setup pipeline", zap.Error(err), zap.String("repository", repositoryList[0].repository.ExternalID))+ slog.Error("failed to setup pipeline", log.BBError(err), slog.String("repository", repositoryList[0].repository.ExternalID))return echo.NewHTTPError(http.StatusInternalServerError, "Failed to setup SQL review pipeline").SetInternal(err)}return c.String(http.StatusOK, "OK")@@ -556,9 +556,9 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {if err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Failed to read SQL review request").SetInternal(err)}- log.Debug("SQL review request received for VCS project",- zap.String("webhook_endpoint_id", c.Param("id")),- zap.String("request", string(body)),+ slog.Debug("SQL review request received for VCS project",+ slog.String("webhook_endpoint_id", c.Param("id")),+ slog.String("request", string(body)),)setting, err := s.store.GetWorkspaceGeneralSetting(ctx)@@ -580,17 +580,17 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {filter := func(repo *store.RepositoryMessage) (bool, error) {if !repo.EnableSQLReviewCI {- log.Debug("Skip repository as the SQL review CI is not enabled.",- zap.Int("repository_id", repo.UID),- zap.String("repository_external_id", repo.ExternalID),+ slog.Debug("Skip repository as the SQL review CI is not enabled.",+ slog.Int("repository_id", repo.UID),+ slog.String("repository_external_id", repo.ExternalID),)return false, nil}if !strings.HasPrefix(repo.WebURL, request.WebURL) {- log.Debug("Skip repository as the web URL is not matched.",- zap.String("request_web_url", request.WebURL),- zap.String("repo_web_url", repo.WebURL),+ slog.Debug("Skip repository as the web URL is not matched.",+ slog.String("request_web_url", request.WebURL),+ slog.String("repo_web_url", repo.WebURL),)return false, nil}@@ -608,7 +608,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return err}if len(repositoryList) == 0 {- log.Debug("Empty handle repo list. Ignore this request.")+ slog.Debug("Empty handle repo list. Ignore this request.")return c.JSON(http.StatusOK, &api.VCSSQLReviewResult{Status: advisor.Success,Content: []string{},@@ -703,12 +703,12 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {response = convertSQLAdviceToGitLabCIResult(sqlFileName2Advice)}- log.Debug("SQL review finished",- zap.String("pull_request", request.PullRequestID),- zap.String("status", string(response.Status)),- zap.String("content", strings.Join(response.Content, "\n")),- zap.String("repository_id", request.RepositoryID),- zap.String("vcs", string(repo.vcs.Type)),+ slog.Debug("SQL review finished",+ slog.String("pull_request", request.PullRequestID),+ slog.String("status", string(response.Status)),+ slog.String("content", strings.Join(response.Content, "\n")),+ slog.String("repository_id", request.RepositoryID),+ slog.String("vcs", string(repo.vcs.Type)),)return c.JSON(http.StatusOK, response)@@ -730,9 +730,9 @@ func (s *Server) sqlAdviceForMybatisMapperFiles(ctx context.Context, mybatisMapp}var wg sync.WaitGroupfor _, mybatisMapperXMLFile := range mybatisMapperXMLFileData {- log.Debug("Mybatis mapper xml file data",- zap.String("mapper file", mybatisMapperXMLFile.mapperPath),- zap.String("config file", mybatisMapperXMLFile.configPath),+ slog.Debug("Mybatis mapper xml file data",+ slog.String("mapper file", mybatisMapperXMLFile.mapperPath),+ slog.String("config file", mybatisMapperXMLFile.configPath),)if mybatisMapperXMLFile.configContent == "" {continue@@ -742,11 +742,11 @@ func (s *Server) sqlAdviceForMybatisMapperFiles(ctx context.Context, mybatisMappdefer wg.Done()adviceList, err := s.sqlAdviceForMybatisMapperFile(ctx, datum)if err != nil {- log.Error(+ slog.Error("Failed to take SQL review for file",- zap.String("file", datum.mapperContent),- zap.String("repository", repoInfo.repository.WebURL),- zap.Error(err),+ slog.String("file", datum.mapperContent),+ slog.String("repository", repoInfo.repository.WebURL),+ log.BBError(err),)sqlCheckAdvices[datum.configPath] = []advisor.Advice{{@@ -789,7 +789,7 @@ func (s *Server) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatpolicy, err := s.store.GetSQLReviewPolicy(ctx, env.UID)if err != nil {if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {- log.Debug("Cannot found SQL review policy in environment", zap.String("Environment", confEnv.ID), zap.Error(err))+ slog.Debug("Cannot found SQL review policy in environment", slog.String("Environment", confEnv.ID), log.BBError(err))continue}return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to get SQL review policy").SetInternal(err)@@ -884,11 +884,11 @@ func (s *Server) sqlAdviceForSQLFiles(defer wg.Done()adviceList, err := s.sqlAdviceForFile(ctx, file, externalURL)if err != nil {- log.Error(+ slog.Error("Failed to take SQL review for file",- zap.String("file", file.item.FileName),- zap.String("external_id", file.repoInfo.repository.ExternalID),- zap.Error(err),+ slog.String("file", file.item.FileName),+ slog.String("external_id", file.repoInfo.repository.ExternalID),+ log.BBError(err),)sqlCheckAdvice[file.item.FileName] = []advisor.Advice{{@@ -914,9 +914,9 @@ func (s *Server) sqlAdviceForFile(fileInfo fileInfo,externalURL string,) ([]advisor.Advice, error) {- log.Debug("Processing file",- zap.String("file", fileInfo.item.FileName),- zap.String("vcs", string(fileInfo.repoInfo.vcs.Type)),+ slog.Debug("Processing file",+ slog.String("file", fileInfo.item.FileName),+ slog.String("vcs", string(fileInfo.repoInfo.vcs.Type)),)// TODO: support tenant mode project@@ -936,12 +936,12 @@ func (s *Server) sqlAdviceForFile(// We can use https://github.com/bytebase/bytebase/blob/main/server/issue.go#L691 to find databases in tenant mode project.databases, err := s.findProjectDatabases(ctx, fileInfo.repoInfo.project.UID, fileInfo.migrationInfo.Database, fileInfo.migrationInfo.Environment)if err != nil {- log.Debug(+ slog.Debug("Failed to list database migration info",- zap.String("project", fileInfo.repoInfo.repository.ProjectResourceID),- zap.String("database", fileInfo.migrationInfo.Database),- zap.String("environment", fileInfo.migrationInfo.Environment),- zap.Error(err),+ slog.String("project", fileInfo.repoInfo.repository.ProjectResourceID),+ slog.String("database", fileInfo.migrationInfo.Database),+ slog.String("environment", fileInfo.migrationInfo.Environment),+ log.BBError(err),)return nil, errors.Errorf("Failed to list databse with error: %v", err)}@@ -979,7 +979,7 @@ func (s *Server) sqlAdviceForFile(return nil, errors.Errorf("cannot found instance %s", database.InstanceID)}if err := s.licenseService.IsFeatureEnabledForInstance(api.FeatureVCSSQLReviewWorkflow, instance); err != nil {- log.Debug(err.Error(), zap.String("instance", instance.ResourceID))+ slog.Debug(err.Error(), slog.String("instance", instance.ResourceID))continue}@@ -993,7 +993,7 @@ func (s *Server) sqlAdviceForFile(policy, err := s.store.GetSQLReviewPolicy(ctx, environment.UID)if err != nil {if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {- log.Debug("Cannot found SQL review policy in environment", zap.String("Environment", database.EffectiveEnvironmentID), zap.Error(err))+ slog.Debug("Cannot found SQL review policy in environment", slog.String("Environment", database.EffectiveEnvironmentID), log.BBError(err))continue}return nil, errors.Errorf("Failed to get SQL review policy in environment %v with error: %v", instance.EnvironmentID, err)@@ -1076,31 +1076,31 @@ func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string,ShowDeleted: false,})if err != nil {- log.Error("failed to find the project",- zap.String("project_resource_id", repo.ProjectResourceID),- zap.String("repository_external_id", repo.ExternalID),+ slog.Error("failed to find the project",+ slog.String("project_resource_id", repo.ProjectResourceID),+ slog.String("repository_external_id", repo.ExternalID),)continue}if project == nil {- log.Debug("skipping repo due to missing project",- zap.String("project_resource_id", repo.ProjectResourceID),- zap.String("repository_external_id", repo.ExternalID),+ slog.Debug("skipping repo due to missing project",+ slog.String("project_resource_id", repo.ProjectResourceID),+ slog.String("repository_external_id", repo.ExternalID),)continue}externalVCS, err := s.store.GetExternalVersionControlV2(ctx, repo.VCSUID)if err != nil {- log.Error("failed to find the vcs",- zap.Int("vcs_uid", repo.VCSUID),- zap.String("repository_external_id", repo.ExternalID),+ slog.Error("failed to find the vcs",+ slog.Int("vcs_uid", repo.VCSUID),+ slog.String("repository_external_id", repo.ExternalID),)continue}if externalVCS == nil {- log.Debug("skipping repo due to missing VCS",- zap.Int("vcs_uid", repo.VCSUID),- zap.String("repository_external_id", repo.ExternalID),+ slog.Debug("skipping repo due to missing VCS",+ slog.Int("vcs_uid", repo.VCSUID),+ slog.String("repository_external_id", repo.ExternalID),)continue}@@ -1108,12 +1108,12 @@ func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string,switch externalVCS.Type {case vcs.AzureDevOps:if !strings.HasSuffix(repo.ExternalID, pushEventRepositoryID) {- log.Debug("Skipping repo due to external ID mismatch", zap.Int("repoID", repo.UID), zap.String("pushEventExternalID", pushEventRepositoryID), zap.String("repoExternalID", repo.ExternalID))+ slog.Debug("Skipping repo due to external ID mismatch", slog.Int("repoID", repo.UID), slog.String("pushEventExternalID", pushEventRepositoryID), slog.String("repoExternalID", repo.ExternalID))continue}default:if pushEventRepositoryID != repo.ExternalID {- log.Debug("Skipping repo due to external ID mismatch", zap.Int("repoID", repo.UID), zap.String("pushEventExternalID", pushEventRepositoryID), zap.String("repoExternalID", repo.ExternalID))+ slog.Debug("Skipping repo due to external ID mismatch", slog.Int("repoID", repo.UID), slog.String("pushEventExternalID", pushEventRepositoryID), slog.String("repoExternalID", repo.ExternalID))continue}}@@ -1123,7 +1123,7 @@ func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string,return nil, err}if !ok {- log.Debug("Skipping repo due to mismatched payload signature", zap.Int("repoID", repo.UID))+ slog.Debug("Skipping repo due to mismatched payload signature", slog.Int("repoID", repo.UID))continue}@@ -1146,7 +1146,7 @@ func (*Server) isWebhookEventBranch(pushEventRef, branchFilter string) (bool, erreturn false, errors.Wrapf(err, "failed to match branch filter")}if !ok {- log.Debug("Skipping repo due to branch filter mismatch", zap.String("branch", branch), zap.String("filter", branchFilter))+ slog.Debug("Skipping repo due to branch filter mismatch", slog.String("branch", branch), slog.String("filter", branchFilter))return false, nil}return true, nil@@ -1174,10 +1174,10 @@ func validateGitHubWebhookSignature256(signature, key string, body []byte) (boolfunc parseBranchNameFromRefs(ref string) (string, error) {expectedPrefix := "refs/heads/"if !strings.HasPrefix(ref, expectedPrefix) || len(expectedPrefix) == len(ref) {- log.Debug(+ slog.Debug("ref is not prefix with expected prefix",- zap.String("ref", ref),- zap.String("expected prefix", expectedPrefix),+ slog.String("ref", ref),+ slog.String("expected prefix", expectedPrefix),)return ref, errors.Errorf("unexpected ref name %q without prefix %q", ref, expectedPrefix)}@@ -1195,10 +1195,10 @@ func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo,for _, c := range baseVCSPushEvent.CommitList {commitIDs = append(commitIDs, c.ID)}- log.Warn("No files found from the push event",- zap.String("repoURL", baseVCSPushEvent.RepositoryURL),- zap.String("repoName", baseVCSPushEvent.RepositoryFullPath),- zap.String("commits", strings.Join(commitIDs, ",")))+ slog.Warn("No files found from the push event",+ slog.String("repoURL", baseVCSPushEvent.RepositoryURL),+ slog.String("repoName", baseVCSPushEvent.RepositoryFullPath),+ slog.String("commits", strings.Join(commitIDs, ",")))return nil, nil}@@ -1241,7 +1241,7 @@ func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo,} else {for _, activityCreate := range activityCreateList {if _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{}); err != nil {- log.Warn("Failed to create project activity for the ignored repository files", zap.Error(err))+ slog.Warn("Failed to create project activity for the ignored repository files", log.BBError(err))}}}@@ -1253,7 +1253,7 @@ func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo,for _, repoInfo := range repoInfoList {repoURLs = append(repoURLs, repoInfo.repository.WebURL)}- log.Warn("Ignored push event because no applicable file found in the commit list", zap.Strings("repos", repoURLs))+ slog.Warn("Ignored push event because no applicable file found in the commit list", slog.Any("repos", repoURLs))}return createdMessageList, nil@@ -1322,12 +1322,12 @@ func groupFileInfoByDatabase(fileInfoList []fileInfo) map[string][]fileInfo {func groupFileInfoByRepo(distinctFileList []vcs.DistinctFileItem, repoInfoList []*repoInfo) map[int][]fileInfo {repoID2FileItemList := make(map[int][]fileInfo)for _, item := range distinctFileList {- log.Debug("Processing file", zap.String("file", item.FileName), zap.String("commit", item.Commit.ID))+ slog.Debug("Processing file", slog.String("file", item.FileName), slog.String("commit", item.Commit.ID))migrationInfo, fType, repoInfo, err := getFileInfo(item, repoInfoList)if err != nil {- log.Warn("Failed to get file info for the ignored repository file",- zap.String("file", item.FileName),- zap.Error(err),+ slog.Warn("Failed to get file info for the ignored repository file",+ slog.String("file", item.FileName),+ log.BBError(err),)continue}@@ -1359,9 +1359,9 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.Mvar fileRepositoryList []*repoInfofor _, repoInfo := range repoInfoList {if !strings.HasPrefix(fileItem.FileName, repoInfo.repository.BaseDirectory) {- log.Debug("Ignored file outside the base directory",- zap.String("file", fileItem.FileName),- zap.String("base_directory", repoInfo.repository.BaseDirectory),+ slog.Debug("Ignored file outside the base directory",+ slog.String("file", fileItem.FileName),+ slog.String("base_directory", repoInfo.repository.BaseDirectory),)continue}@@ -1381,10 +1381,10 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.Mmi, err := db.ParseMigrationInfo(fileItem.FileName, filePathTemplate, allowOmitDatabaseName)if err != nil {- log.Error("Failed to parse migration file info",- zap.String("project", repoInfo.repository.ProjectResourceID),- zap.String("file", fileItem.FileName),- zap.Error(err),+ slog.Error("Failed to parse migration file info",+ slog.String("project", repoInfo.repository.ProjectResourceID),+ slog.String("file", fileItem.FileName),+ log.BBError(err),)continue}@@ -1401,9 +1401,9 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.Msi, err := db.ParseSchemaFileInfo(repoInfo.repository.BaseDirectory, repoInfo.repository.SchemaPathTemplate, fileItem.FileName)if err != nil {- log.Debug("Failed to parse schema file info",- zap.String("file", fileItem.FileName),- zap.Error(err),+ slog.Debug("Failed to parse schema file info",+ slog.String("file", fileItem.FileName),+ log.BBError(err),)continue}@@ -1464,7 +1464,7 @@ func (s *Server) processFilesInProject(ctx context.Context, pushEvent vcs.PushEvcreatedIssueList = append(createdIssueList, issueName)}} else {- log.Debug("Ignored schema file for non-SDL project", zap.String("fileName", fileInfo.item.FileName), zap.String("type", string(fileInfo.item.ItemType)))+ slog.Debug("Ignored schema file for non-SDL project", slog.String("fileName", fileInfo.item.FileName), slog.String("type", string(fileInfo.item.ItemType)))}} else { // fileInfo.fType == fileTypeMigration// This is a migration-based DDL or DML file and we would allow it for both DDL and SDL schema change type project.@@ -1687,9 +1687,9 @@ func (s *Server) getIssueCreatorID(ctx context.Context, email string) int {Email: &email,})if err != nil {- log.Warn("Failed to find the principal with committer email, use system bot instead", zap.String("email", email), zap.Error(err))+ slog.Warn("Failed to find the principal with committer email, use system bot instead", slog.String("email", email), log.BBError(err))} else if committerPrincipal == nil {- log.Info("Principal with committer email does not exist, use system bot instead", zap.String("email", email))+ slog.Info("Principal with committer email does not exist, use system bot instead", slog.String("email", email))} else {creatorID = committerPrincipal.ID}@@ -1783,8 +1783,8 @@ func getIgnoredFileActivityCreate(projectID int, pushEvent vcs.PushEvent, file s},)if marshalErr != nil {- log.Warn("Failed to construct project activity payload for the ignored repository file",- zap.Error(marshalErr),+ slog.Warn("Failed to construct project activity payload for the ignored repository file",+ log.BBError(marshalErr),)return nil}@@ -1849,7 +1849,7 @@ func (s *Server) readFileContent(ctx context.Context, pushEvent vcs.PushEvent, rfunc (s *Server) prepareIssueFromSDLFile(ctx context.Context, repoInfo *repoInfo, pushEvent vcs.PushEvent, schemaInfo *db.MigrationInfo, file string) ([]*api.MigrationDetail, []*store.ActivityMessage) {dbName := schemaInfo.Databaseif dbName == "" && repoInfo.project.TenantMode == api.TenantModeDisabled {- log.Debug("Ignored schema file without a database name", zap.String("file", file))+ slog.Debug("Ignored schema file without a database name", slog.String("file", file))return nil, nil}@@ -2084,17 +2084,17 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [continue}if len(taskList) > 1 {- log.Error("Found more than one pending approval or failed tasks for modified VCS file, should be only one task.", zap.Int("databaseID", database.UID), zap.String("schemaVersion", schemaVersion))+ slog.Error("Found more than one pending approval or failed tasks for modified VCS file, should be only one task.", slog.Int("databaseID", database.UID), slog.String("schemaVersion", schemaVersion))return nil}task := taskList[0]issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})if err != nil {- log.Error("failed to get issue by pipeline ID", zap.Int("pipeline ID", task.PipelineID), zap.Error(err))+ slog.Error("failed to get issue by pipeline ID", slog.Int("pipeline ID", task.PipelineID), log.BBError(err))return nil}if issue == nil {- log.Error("issue not found by pipeline ID", zap.Int("pipeline ID", task.PipelineID), zap.Error(err))+ slog.Error("issue not found by pipeline ID", slog.Int("pipeline ID", task.PipelineID), log.BBError(err))return nil}@@ -2118,21 +2118,21 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [}// TODO(dragonly): Try to patch the failed migration history record to pending, and the statement to the current modified file content.- log.Debug("Patching task for modified file VCS push event", zap.String("fileName", fileName), zap.Int("issueID", issue.UID), zap.Int("taskID", task.ID))+ slog.Debug("Patching task for modified file VCS push event", slog.String("fileName", fileName), slog.Int("issueID", issue.UID), slog.Int("taskID", task.ID))taskPatch := api.TaskPatch{ID: task.ID,SheetID: &sheet.UID,UpdaterID: api.SystemBotID,}if err := patchTask(ctx, s.store, s.ActivityManager, task, &taskPatch, issue); err != nil {- log.Error("Failed to patch task with the same migration version", zap.Int("issueID", issue.UID), zap.Int("taskID", task.ID), zap.Error(err))+ slog.Error("Failed to patch task with the same migration version", slog.Int("issueID", issue.UID), slog.Int("taskID", task.ID), log.BBError(err))return nil}if issue.PlanUID != nil {plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{UID: issue.PlanUID})if err != nil {- log.Error("failed to get plan", zap.Int64("plan ID", *issue.PlanUID), zap.Error(err))+ slog.Error("failed to get plan", slog.Int64("plan ID", *issue.PlanUID), log.BBError(err))}for _, step := range plan.Config.Steps {for _, spec := range step.Specs {@@ -2150,7 +2150,7 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [Config: plan.Config,UpdaterID: api.SystemBotID,}); err != nil {- log.Error("failed to update plan", zap.Int64("plan ID", *issue.PlanUID), zap.Error(err))+ slog.Error("failed to update plan", slog.Int64("plan ID", *issue.PlanUID), log.BBError(err))}}@@ -2181,7 +2181,7 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [s.stateCfg.ApprovalFinding.Store(issue.UID, issue)return nil}(); err != nil {- log.Error("Failed to dismiss stale review", zap.Error(err))+ slog.Error("Failed to dismiss stale review", log.BBError(err))}}return nildiff --git a/backend/sql-server/metric.go b/backend/sql-server/metric.goindex d317e74115..41764b5b5e 100644--- a/backend/sql-server/metric.go+++ b/backend/sql-server/metric.go@@ -1,11 +1,11 @@package sqlserverimport (+ "log/slog""strconv""time""github.com/labstack/echo/v4"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common/log"metricAPI "github.com/bytebase/bytebase/backend/metric"@@ -23,10 +23,10 @@ func (m *metricReporter) Report(metric *metric.Metric) {}if err := m.reporter.Report(m.workspaceID, metric); err != nil {- log.Error(+ slog.Error("Failed to report metric",- zap.String("metric", string(metricAPI.OpenAPIMetricName)),- zap.Error(err),+ slog.String("metric", string(metricAPI.OpenAPIMetricName)),+ log.BBError(err),)}}diff --git a/backend/sql-server/server.go b/backend/sql-server/server.goindex 8e42d06722..5c474b9a29 100644--- a/backend/sql-server/server.go+++ b/backend/sql-server/server.go@@ -4,6 +4,7 @@ package sqlserverimport ("context""fmt"+ "log/slog""net/http""time"@@ -18,7 +19,6 @@ import ("github.com/labstack/echo/v4/middleware""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log")// Server is the Bytebase server.@@ -60,12 +60,12 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {}// Display config- log.Info("-----Config BEGIN-----")- log.Info(fmt.Sprintf("mode=%s", prof.Mode))- log.Info(fmt.Sprintf("server=%s:%d", prof.BackendHost, prof.BackendPort))- log.Info(fmt.Sprintf("debug=%t", prof.Debug))- log.Info(fmt.Sprintf("workspaceID=%s", prof.WorkspaceID))- log.Info("-----Config END-------")+ slog.Info("-----Config BEGIN-----")+ slog.Info(fmt.Sprintf("mode=%s", prof.Mode))+ slog.Info(fmt.Sprintf("server=%s:%d", prof.BackendHost, prof.BackendPort))+ slog.Info(fmt.Sprintf("debug=%t", prof.Debug))+ slog.Info(fmt.Sprintf("workspaceID=%s", prof.WorkspaceID))+ slog.Info("-----Config END-------")serverStarted := falsedefer func() {@@ -119,8 +119,8 @@ func (s *Server) Run() error {// Shutdown will shut down the server.func (s *Server) Shutdown(ctx context.Context) error {- log.Info("Trying to stop Bytebase SQL Service ....")- log.Info("Trying to gracefully shutdown server")+ slog.Info("Trying to stop Bytebase SQL Service ....")+ slog.Info("Trying to gracefully shutdown server")ctx, cancel := context.WithTimeout(ctx, 10*time.Second)defer cancel()@@ -132,7 +132,7 @@ func (s *Server) Shutdown(ctx context.Context) error {}}- log.Info("Bytebase SQL Service stopped properly")+ slog.Info("Bytebase SQL Service stopped properly")return nil}diff --git a/backend/store/backup.go b/backend/store/backup.goindex 8930b87b24..0f16f04a86 100644--- a/backend/store/backup.go+++ b/backend/store/backup.go@@ -5,10 +5,10 @@ import ("database/sql""encoding/json""fmt"+ "log/slog""strings""github.com/pkg/errors"- "go.uber.org/zap/zapcore""github.com/bytebase/bytebase/backend/common"api "github.com/bytebase/bytebase/backend/legacyapi"@@ -153,19 +153,21 @@ type BackupMessage struct {Payload api.BackupPayload}-// ZapBackupArray is a helper to format zap.Array.-type ZapBackupArray []*BackupMessage+// SLogBackupArray is a helper to format []*BackupMessage.+type SLogBackupArray []*BackupMessage-// MarshalLogArray implements the zapcore.ArrayMarshaler interface.-func (backups ZapBackupArray) MarshalLogArray(arr zapcore.ArrayEncoder) error {+// LogValue implements the LogValuer interface.+func (backups SLogBackupArray) LogValue() slog.Value {+ backupList := []string{}for _, backup := range backups {payload, err := json.Marshal(backup.Payload)if err != nil {- return err+ backupList = append(backupList, err.Error())+ continue}- arr.AppendString(fmt.Sprintf("{name:%s, id:%d, payload:%s}", backup.Name, backup.UID, payload))+ backupList = append(backupList, fmt.Sprintf("{name:%s, id:%d, payload:%s}", backup.Name, backup.UID, payload))}- return nil+ return slog.StringValue(strings.Join(backupList, ","))}// FindBackupMessage is the message for finding backup.diff --git a/backend/store/metadb.go b/backend/store/metadb.goindex e8a8bd576c..c4e259df59 100644--- a/backend/store/metadb.go+++ b/backend/store/metadb.go@@ -2,14 +2,13 @@ package storeimport ("fmt"+ "log/slog""net""net/url""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log"dbdriver "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/resources/postgres")@@ -92,7 +91,7 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)q := u.Query()- log.Info("Establishing external PostgreSQL connection...", zap.String("pgURL", u.Redacted()))+ slog.Info("Establishing external PostgreSQL connection...", slog.String("pgURL", u.Redacted()))// Though the official libpq adopts postgresql:// (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING)// Several popular services such as render.com, supabase use postgres://.@@ -162,7 +161,7 @@ func (m *MetadataDB) Close() error {return nil}- log.Info("Stopping PostgreSQL...")+ slog.Info("Stopping PostgreSQL...")if err := postgres.Stop(m.binDir, m.pgDataDir); err != nil {return err}diff --git a/backend/store/pg_engine_log.go b/backend/store/pg_engine_log.goindex af45e21703..bcf93811ed 100644--- a/backend/store/pg_engine_log.go+++ b/backend/store/pg_engine_log.go@@ -7,11 +7,8 @@ package storeimport ("context""database/sql"+ "log/slog""regexp"-- "go.uber.org/zap"-- "github.com/bytebase/bytebase/backend/common/log")// Replace mutiple whitespace characters including /t/n with a single space.@@ -23,24 +20,24 @@ func cleanQuery(query string) string {// PrepareContext overrides sql.Tx PrepareContext.func (tx *Tx) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {- log.Debug("PrepareContext", zap.String("query", cleanQuery(query)))+ slog.Debug("PrepareContext", slog.String("query", cleanQuery(query)))return tx.Tx.PrepareContext(ctx, query)}// ExecContext overrides sql.Tx ExecContext.func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {- log.Debug("ExecContext", zap.String("query", cleanQuery(query)))+ slog.Debug("ExecContext", slog.String("query", cleanQuery(query)))return tx.Tx.ExecContext(ctx, query, args...)}// QueryContext overrides sql.Tx QueryContext.func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {- log.Debug("QueryContext", zap.String("query", cleanQuery(query)))+ slog.Debug("QueryContext", slog.String("query", cleanQuery(query)))return tx.Tx.QueryContext(ctx, query, args...)}// QueryRowContext overrides sql.Tx QueryRowContext.func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row {- log.Debug("QueryRowContext", zap.String("query", cleanQuery(query)))+ slog.Debug("QueryRowContext", slog.String("query", cleanQuery(query)))return tx.Tx.QueryRowContext(ctx, query, args...)}diff --git a/backend/tests/backup_restore_test.go b/backend/tests/backup_restore_test.goindex 5888204b35..f4b7e5324f 100644--- a/backend/tests/backup_restore_test.go+++ b/backend/tests/backup_restore_test.go@@ -7,6 +7,7 @@ import ("context""database/sql""fmt"+ "log/slog""os""path/filepath""sort"@@ -17,14 +18,11 @@ import ("google.golang.org/protobuf/types/known/timestamppb"- "github.com/bytebase/bytebase/backend/common/log"api "github.com/bytebase/bytebase/backend/legacyapi"resourcemysql "github.com/bytebase/bytebase/backend/resources/mysql""github.com/bytebase/bytebase/backend/tests/fake"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"- "go.uber.org/zap"-"github.com/stretchr/testify/require")@@ -151,7 +149,7 @@ func TestPITRGeneral(t *testing.T) {targetTs := startUpdateRow(ctxUpdateRow, t, databaseName, mysqlPort).Add(time.Second)dropColumnStmt := `ALTER TABLE tbl1 DROP COLUMN id;`- log.Debug("mimics schema migration", zap.String("statement", dropColumnStmt))+ slog.Debug("mimics schema migration", slog.String("statement", dropColumnStmt))_, err = mysqlDB.ExecContext(ctx, dropColumnStmt)a.NoError(err)@@ -322,7 +320,7 @@ func TestPITRTwice(t *testing.T) {})a.NoError(err)- log.Debug("Creating issue for the first PITR.")+ slog.Debug("Creating issue for the first PITR.")insertRangeData(t, mysqlDB, numRowsTime0, numRowsTime1)ctxUpdateRow, cancelUpdateRow := context.WithCancel(ctx)targetTs := startUpdateRow(ctxUpdateRow, t, databaseName, mysqlPort).Add(time.Second)@@ -379,9 +377,9 @@ func TestPITRTwice(t *testing.T) {validateTbl0(t, mysqlDB, databaseName, numRowsTime1)validateTbl1(t, mysqlDB, databaseName, numRowsTime1)validateTableUpdateRow(t, mysqlDB, databaseName)- log.Debug("First PITR done.")+ slog.Debug("First PITR done.")- log.Debug("Wait for the first PITR auto backup to finish.")+ slog.Debug("Wait for the first PITR auto backup to finish.")resp, err := ctl.databaseServiceClient.ListBackups(ctx, &v1pb.ListBackupsRequest{Parent: database.Name,})@@ -394,7 +392,7 @@ func TestPITRTwice(t *testing.T) {err = ctl.waitBackup(ctx, database.Name, backups[0].Name)a.NoError(err)- log.Debug("Creating issue for the second PITR.")+ slog.Debug("Creating issue for the second PITR.")ctxUpdateRow, cancelUpdateRow = context.WithCancel(ctx)targetTs = startUpdateRow(ctxUpdateRow, t, databaseName, mysqlPort).Add(time.Second)insertRangeData(t, mysqlDB, numRowsTime1, numRowsTime2)@@ -452,7 +450,7 @@ func TestPITRTwice(t *testing.T) {validateTbl0(t, mysqlDB, databaseName, numRowsTime1)validateTbl1(t, mysqlDB, databaseName, numRowsTime1)validateTableUpdateRow(t, mysqlDB, databaseName)- log.Debug("Second PITR done.")+ slog.Debug("Second PITR done.")}func TestPITRToNewDatabaseInAnotherInstance(t *testing.T) {@@ -490,7 +488,7 @@ func TestPITRToNewDatabaseInAnotherInstance(t *testing.T) {targetTs := startUpdateRow(ctxUpdateRow, t, databaseName, mysqlPort).Add(time.Second)dropColumnStmt := `ALTER TABLE tbl1 DROP COLUMN id;`- log.Debug("mimics schema migration", zap.String("statement", dropColumnStmt))+ slog.Debug("mimics schema migration", slog.String("statement", dropColumnStmt))_, err = sourceMySQLDB.ExecContext(ctx, dropColumnStmt)a.NoError(err)@@ -666,7 +664,7 @@ func setUpForPITRTest(ctx context.Context, t *testing.T, ctl *controller) (conteinsertRangeData(t, mysqlDB, 0, numRowsTime0)- log.Debug("Create a full backup")+ slog.Debug("Create a full backup")backup, err := ctl.databaseServiceClient.CreateBackup(ctx, &v1pb.CreateBackupRequest{Parent: database.Name,Backup: &v1pb.Backup{@@ -716,7 +714,7 @@ func initPITRDB(t *testing.T, database string, port int) *sql.DB {}func insertRangeData(t *testing.T, db *sql.DB, begin, end int) {- log.Debug("Inserting range data", zap.Int("begin", begin), zap.Int("end", end))+ slog.Debug("Inserting range data", slog.Int("begin", begin), slog.Int("end", end))a := require.New(t)tx, err := db.Begin()a.NoError(err)@@ -733,7 +731,7 @@ func insertRangeData(t *testing.T, db *sql.DB, begin, end int) {}func validateTbl0(t *testing.T, db *sql.DB, databaseName string, numRows int) {- log.Debug("Validate table tbl0")+ slog.Debug("Validate table tbl0")a := require.New(t)rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s.tbl0;", databaseName))a.NoError(err)@@ -750,7 +748,7 @@ func validateTbl0(t *testing.T, db *sql.DB, databaseName string, numRows int) {}func validateTbl1(t *testing.T, db *sql.DB, databaseName string, numRows int) {- log.Debug("Validate table tbl1")+ slog.Debug("Validate table tbl1")a := require.New(t)rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s.tbl1;", databaseName))a.NoError(err)@@ -768,7 +766,7 @@ func validateTbl1(t *testing.T, db *sql.DB, databaseName string, numRows int) {}func validateTableUpdateRow(t *testing.T, db *sql.DB, databaseName string) {- log.Debug("Validate table _update_row_")+ slog.Debug("Validate table _update_row_")a := require.New(t)rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s._update_row_;", databaseName))a.NoError(err)@@ -790,7 +788,7 @@ func startUpdateRow(ctx context.Context, t *testing.T, database string, port intdb, err := connectTestMySQL(port, database)a.NoError(err)- log.Debug("Start updating data concurrently")+ slog.Debug("Start updating data concurrently")initTimestamp := time.Now()// Sleep for one second so that the concurrent update will start no earlier than initTimestamp+1.@@ -811,7 +809,7 @@ func startUpdateRow(ctx context.Context, t *testing.T, database string, port inta.NoError(err)i++case <-ctx.Done():- log.Debug("Stop updating data concurrently")+ slog.Debug("Stop updating data concurrently")return}}diff --git a/backend/tests/data_source_test.go b/backend/tests/data_source_test.goindex 8505e75966..1ba427eb4f 100644--- a/backend/tests/data_source_test.go+++ b/backend/tests/data_source_test.go@@ -2,10 +2,10 @@ package testsimport ("context"+ "log/slog""testing""github.com/stretchr/testify/require"- "go.uber.org/zap/zapcore""google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common/log"@@ -15,7 +15,7 @@ import (func TestDataSource(t *testing.T) {a := require.New(t)- log.SetLevel(zapcore.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)ctx := context.Background()ctl := &controller{}dataDir := t.TempDir()diff --git a/backend/tests/database.go b/backend/tests/database.goindex ee7286a538..c4b74c6c83 100644--- a/backend/tests/database.go+++ b/backend/tests/database.go@@ -4,15 +4,14 @@ import ("context""encoding/json""fmt"+ "log/slog""strings""time""github.com/google/jsonapi""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/protobuf/types/known/durationpb"- "github.com/bytebase/bytebase/backend/common/log"api "github.com/bytebase/bytebase/backend/legacyapi"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -215,7 +214,7 @@ func (ctl *controller) waitBackup(ctx context.Context, databaseName, backupNameticker := time.NewTicker(100 * time.Millisecond)defer ticker.Stop()- log.Debug("Waiting for backup.", zap.String("id", backupName))+ slog.Debug("Waiting for backup.", slog.String("id", backupName))for range ticker.C {resp, err := ctl.databaseServiceClient.ListBackups(ctx, &v1pb.ListBackupsRequest{Parent: databaseName})if err != nil {@@ -248,7 +247,7 @@ func (ctl *controller) waitBackupArchived(ctx context.Context, databaseName, bacticker := time.NewTicker(100 * time.Millisecond)defer ticker.Stop()- log.Debug("Waiting for backup.", zap.String("id", backupName))+ slog.Debug("Waiting for backup.", slog.String("id", backupName))for range ticker.C {resp, err := ctl.databaseServiceClient.ListBackups(ctx, &v1pb.ListBackupsRequest{Parent: databaseName})if err != nil {diff --git a/backend/tests/environment_test.go b/backend/tests/environment_test.goindex 9d7c8a85b2..6f42f6c628 100644--- a/backend/tests/environment_test.go+++ b/backend/tests/environment_test.go@@ -3,10 +3,10 @@ package testsimport ("context""fmt"+ "log/slog""testing""github.com/stretchr/testify/require"- "go.uber.org/zap/zapcore""google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common/log"@@ -16,7 +16,7 @@ import (func TestDatabaseEnvironment(t *testing.T) {a := require.New(t)- log.SetLevel(zapcore.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)ctx := context.Background()ctl := &controller{}dataDir := t.TempDir()diff --git a/backend/tests/project_test.go b/backend/tests/project_test.goindex 6fa8dcbe14..cb69abf682 100644--- a/backend/tests/project_test.go+++ b/backend/tests/project_test.go@@ -3,10 +3,10 @@ package testsimport ("context""fmt"+ "log/slog""testing""github.com/stretchr/testify/require"- "go.uber.org/zap/zapcore""github.com/bytebase/bytebase/backend/common/log"api "github.com/bytebase/bytebase/backend/legacyapi"@@ -16,7 +16,7 @@ import (func TestArchiveProject(t *testing.T) {a := require.New(t)- log.SetLevel(zapcore.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)ctx := context.Background()ctl := &controller{}dataDir := t.TempDir()diff --git a/backend/tests/subscription_test.go b/backend/tests/subscription_test.goindex d4125d3a7b..fb5cc4705b 100644--- a/backend/tests/subscription_test.go+++ b/backend/tests/subscription_test.go@@ -2,10 +2,10 @@ package testsimport ("context"+ "log/slog""testing""github.com/stretchr/testify/require"- "go.uber.org/zap/zapcore""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/tests/fake"@@ -22,7 +22,7 @@ type trial struct {func TestSubscription(t *testing.T) {a := require.New(t)- log.SetLevel(zapcore.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)ctx := context.Background()ctl := &controller{}dataDir := t.TempDir()diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex 44da4c1023..e19bba34d9 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -7,6 +7,7 @@ import (_ "embed""fmt""io"+ "log/slog""net/http""net/url""os"@@ -17,7 +18,6 @@ import ("github.com/pkg/errors""go.uber.org/multierr"- "go.uber.org/zap""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure""google.golang.org/grpc/metadata"@@ -241,7 +241,7 @@ func getTestDatabaseString() string {// StartServerWithExternalPg starts the main server with external Postgres.func (ctl *controller) StartServerWithExternalPg(ctx context.Context, config *config) (context.Context, error) {- log.SetLevel(zap.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)if err := ctl.startMockServers(config.vcsProviderCreator, config.feishuProverdierCreator); err != nil {return nil, err}@@ -282,7 +282,7 @@ func (ctl *controller) StartServerWithExternalPg(ctx context.Context, config *co// StartServer starts the main server with embed Postgres.func (ctl *controller) StartServer(ctx context.Context, config *config) (context.Context, error) {- log.SetLevel(zap.DebugLevel)+ log.GLogLevel.Set(slog.LevelDebug)if err := ctl.startMockServers(config.vcsProviderCreator, config.feishuProverdierCreator); err != nil {return nil, err}@@ -534,12 +534,12 @@ func (ctl *controller) waitForHealthz() error {gURL := fmt.Sprintf("%s/auth/login", ctl.v1APIURL)req, err := http.NewRequest(http.MethodPost, gURL, nil)if err != nil {- log.Error("Fail to create a new POST request", zap.String("URL", gURL), zap.Error(err))+ slog.Error("Fail to create a new POST request", slog.String("URL", gURL), log.BBError(err))continue}resp, err := ctl.client.Do(req)if err != nil {- log.Error("Fail to send a POST request", zap.String("URL", gURL), zap.Error(err))+ slog.Error("Fail to send a POST request", slog.String("URL", gURL), log.BBError(err))continue}if resp.StatusCode == http.StatusServiceUnavailable {diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex b9b7efda3a..c54c5e9e66 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -6,6 +6,7 @@ import ("context""encoding/json""fmt"+ "log/slog""reflect""regexp""sort"@@ -16,7 +17,6 @@ import ("github.com/github/gh-ost/go/base"ghostsql "github.com/github/gh-ost/go/sql""github.com/pkg/errors"- "go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/encoding/protojson"@@ -428,9 +428,9 @@ func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, sdefer func() {if err := EndMigration(ctx, s, startedNs, insertedID, updatedSchema, resErr == nil /* isDone */); err != nil {- log.Error("Failed to update migration history record",- zap.Error(err),- zap.String("migration_id", migrationHistoryID),+ slog.Error("Failed to update migration history record",+ log.BBError(err),+ slog.String("migration_id", migrationHistoryID),)}}()@@ -504,7 +504,7 @@ func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInforeturn migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)case db.Pending:err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)- log.Debug(err.Error())+ slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.if m.Force {return migrationHistory.ID, nil@@ -512,7 +512,7 @@ func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInforeturn "", common.Wrap(err, common.MigrationPending)case db.Failed:err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version ", m.Database, m.Version)- log.Debug(err.Error())+ slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.if m.Force {return migrationHistory.ID, nildiff --git a/go.mod b/go.modindex 3fa5804ec7..49b9035242 100644--- a/go.mod+++ b/go.mod@@ -69,7 +69,6 @@ require (github.com/xuri/excelize/v2 v2.7.1go.mongodb.org/mongo-driver v1.12.0go.uber.org/multierr v1.11.0- go.uber.org/zap v1.24.0golang.org/x/crypto v0.10.0golang.org/x/exp v0.0.0-20230626212559-97b1e661b5dfgolang.org/x/oauth2 v0.9.0@@ -132,6 +131,7 @@ require (github.com/xuri/efp v0.0.0-20220603152613-6918739fd470 // indirectgithub.com/xuri/nfp v0.0.0-20220409054826-5e722a1d9e22 // indirectgithub.com/zeebo/xxh3 v1.0.2 // indirect+ go.uber.org/zap v1.24.0 // indirectgolang.org/x/mod v0.11.0 // indirectgolang.org/x/term v0.9.0 // indirect)