-
Notifications
You must be signed in to change notification settings - Fork 0
feat(core): add Postgres query observability #126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
BK1031
wants to merge
3
commits into
bk1031/analytics-query-hardening
from
bk1031/postgres-observability
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/gaucho-racing/sentinel/core/observability" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/prometheus/client_golang/prometheus/promhttp" | ||
| ) | ||
|
|
||
| var prometheusHandler = promhttp.Handler() | ||
|
|
||
| func AnalyticsMetrics() gin.HandlerFunc { | ||
| return func(c *gin.Context) { | ||
| if !strings.HasPrefix(c.Request.URL.Path, "/analytics/") { | ||
| c.Next() | ||
| return | ||
| } | ||
| started := time.Now() | ||
| defer func() { | ||
| observability.ObserveAnalyticsRequest(c.FullPath(), c.Writer.Status(), time.Since(started)) | ||
| }() | ||
| c.Next() | ||
| } | ||
| } | ||
|
|
||
| func Metrics(c *gin.Context) { | ||
| Require(c, RequestTokenHasInternalAccess(c)) | ||
| prometheusHandler.ServeHTTP(c.Writer, c.Request) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| package observability | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "strings" | ||
| "time" | ||
|
|
||
| appLogger "github.com/gaucho-racing/sentinel/core/pkg/logger" | ||
| "gorm.io/gorm" | ||
| "gorm.io/gorm/logger" | ||
| ) | ||
|
|
||
| type DatabaseLogger struct { | ||
| level logger.LogLevel | ||
| slowThreshold time.Duration | ||
| } | ||
|
|
||
| func NewDatabaseLogger(slowThreshold time.Duration) logger.Interface { | ||
| return &DatabaseLogger{level: logger.Warn, slowThreshold: slowThreshold} | ||
| } | ||
|
|
||
| func (l *DatabaseLogger) LogMode(level logger.LogLevel) logger.Interface { | ||
| copy := *l | ||
| copy.level = level | ||
| return © | ||
| } | ||
|
|
||
| func (l *DatabaseLogger) Info(_ context.Context, message string, args ...interface{}) { | ||
| if l.level >= logger.Info { | ||
| appLogger.SugarLogger.Infof(message, args...) | ||
| } | ||
| } | ||
|
|
||
| func (l *DatabaseLogger) Warn(_ context.Context, message string, args ...interface{}) { | ||
| if l.level >= logger.Warn { | ||
| appLogger.SugarLogger.Warnf(message, args...) | ||
| } | ||
| } | ||
|
|
||
| func (l *DatabaseLogger) Error(_ context.Context, message string, args ...interface{}) { | ||
| if l.level >= logger.Error { | ||
| appLogger.SugarLogger.Errorf(message, args...) | ||
| } | ||
| } | ||
|
|
||
| func (l *DatabaseLogger) Trace(_ context.Context, started time.Time, query func() (string, int64), err error) { | ||
| elapsed := time.Since(started) | ||
| sql, rows := query() | ||
| operation := databaseOperation(sql) | ||
| slow := l.slowThreshold > 0 && elapsed >= l.slowThreshold | ||
| ObserveDatabaseQuery(operation, err != nil, slow, elapsed) | ||
|
|
||
| if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) && l.level >= logger.Error { | ||
| appLogger.SugarLogger.Errorf("Database query failed (operation=%s duration=%s rows=%d): %v", operation, elapsed, rows, err) | ||
| return | ||
| } | ||
| if slow && l.level >= logger.Warn { | ||
| appLogger.SugarLogger.Warnf("Slow database query (operation=%s duration=%s rows=%d)", operation, elapsed, rows) | ||
| } | ||
| } | ||
|
|
||
| func databaseOperation(sql string) string { | ||
| fields := strings.Fields(sql) | ||
| if len(fields) == 0 { | ||
| return "OTHER" | ||
| } | ||
| operation := strings.ToUpper(fields[0]) | ||
| switch operation { | ||
| case "SELECT", "INSERT", "UPDATE", "DELETE", "WITH", "CREATE", "ALTER", "DROP": | ||
| return operation | ||
| default: | ||
| return "OTHER" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| package observability | ||
|
|
||
| import ( | ||
| "strconv" | ||
| "time" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| ) | ||
|
|
||
| var analyticsRequestDuration = prometheus.NewHistogramVec( | ||
| prometheus.HistogramOpts{ | ||
| Namespace: "sentinel", | ||
| Subsystem: "analytics", | ||
| Name: "request_duration_seconds", | ||
| Help: "Duration of analytics HTTP requests.", | ||
| Buckets: prometheus.DefBuckets, | ||
| }, | ||
| []string{"route", "status"}, | ||
| ) | ||
|
|
||
| var databaseQueryDuration = prometheus.NewHistogramVec( | ||
| prometheus.HistogramOpts{ | ||
| Namespace: "sentinel", | ||
| Subsystem: "database", | ||
| Name: "query_duration_seconds", | ||
| Help: "Duration of database queries by operation and result.", | ||
| Buckets: prometheus.ExponentialBuckets(0.001, 2, 15), | ||
| }, | ||
| []string{"operation", "result"}, | ||
| ) | ||
|
|
||
| var databaseSlowQueries = prometheus.NewCounterVec( | ||
| prometheus.CounterOpts{ | ||
| Namespace: "sentinel", | ||
| Subsystem: "database", | ||
| Name: "slow_queries_total", | ||
| Help: "Database queries exceeding the configured slow-query threshold.", | ||
| }, | ||
| []string{"operation"}, | ||
| ) | ||
|
|
||
| func init() { | ||
| prometheus.MustRegister(analyticsRequestDuration, databaseQueryDuration, databaseSlowQueries) | ||
| } | ||
|
|
||
| func ObserveAnalyticsRequest(route string, status int, elapsed time.Duration) { | ||
| if route == "" { | ||
| route = "unknown" | ||
| } | ||
| analyticsRequestDuration.WithLabelValues(route, strconv.Itoa(status)).Observe(elapsed.Seconds()) | ||
| } | ||
|
|
||
| func ObserveDatabaseQuery(operation string, failed bool, slow bool, elapsed time.Duration) { | ||
| result := "success" | ||
| if failed { | ||
| result = "error" | ||
| } | ||
| databaseQueryDuration.WithLabelValues(operation, result).Observe(elapsed.Seconds()) | ||
| if slow { | ||
| databaseSlowQueries.WithLabelValues(operation).Inc() | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.