package logs import ( "context" "github.com/samber/lo" "github.com/uptrace/bun" "reflect" "strings" "time" ) var ignoredTableInserts = []string{ "sync_audit", "audit_events", "audit", "communication_logs", "sync_product_variants", "webhook_events", "notification_audit_events", "rollup_age_analysis", "rollup_transactions", "rollup_shipments_charges", "rollup_shipments_events", "rollup_tripsheet", "rollup_branches", "cron_shipment_updates", "cron_delayed_shipment_patch", "orders_rollup", "shipments_rollup", "revenue_rollup", } type ContextWithSuppressDBLog interface { DoSuppressDBLog() bool } type QueryHook struct { IgnoredTableInserts []string Debug bool } func (d QueryHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context { return ctx } func (d QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) { contextWithSuppressDBLog, ok := ctx.(ContextWithSuppressDBLog) if ok { if contextWithSuppressDBLog.DoSuppressDBLog() { return } } sqlQuery := event.Query queryDuration := time.Now().Sub(event.StartTime) queryPrefixesToIgnore := []string{"SELECT", "BEGIN", "COMMIT"} shouldLogQuery := !strings.Contains(sqlQuery, "api_key") // Don't log queries for certain tables ignoredTableInsertsCombined := append(ignoredTableInserts, d.IgnoredTableInserts...) tableName := TableNameForQuery(event) if lo.Contains(ignoredTableInsertsCombined, tableName) { shouldLogQuery = false } if shouldLogQuery { for _, prefixToIgnore := range queryPrefixesToIgnore { if strings.HasPrefix(sqlQuery, prefixToIgnore) { shouldLogQuery = false break } } } if d.Debug || shouldLogQuery { InfoWithFields(map[string]interface{}{"sql": sqlQuery, "t": queryDuration.String()}, "") } return } func TableNameForQuery(event *bun.QueryEvent) string { if event.Model == nil { return "" } model := event.Model.Value() if model == nil { return "" } var modelObject reflect.Type t := reflect.TypeOf(model) pointerToObject := t.Elem() if pointerToObject.Kind() == reflect.Slice { // Object is an array of objects. Get the struct type from the array sliceObject := pointerToObject.Elem() modelObject = sliceObject } else { // Object is a struct modelObject = pointerToObject } tableName := event.DB.Table(modelObject).Name return tableName }