A ent Driver wrapper that logs all database operations using slog.
go get github.com/origadmin/entslog/v3@latestCompatibility: go >= 1.21
No breaking changes will be made to exported APIs before v1.0.0.
import (
"entgo.io/ent/dialect/sql"
"github.com/godcong/entslog"
)
// Wrap your driver with entslog
driver := entslog.New(sql.Open("mysql", "user:password@tcp(localhost:3306)/db?parseTime=true"))
// Use the driver with ent client
client := ent.NewClient(ent.Driver(driver))import "log/slog"
driver := entslog.New(
sql.Open("mysql", dsn),
entslog.WithDefaultLevel(slog.LevelDebug), // Set default log level
entslog.WithErrorLevel(slog.LevelWarn), // Set error log level
)import (
"log/slog"
"os"
)
// Create a custom logger
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
driver := entslog.New(
sql.Open("mysql", dsn),
entslog.WithLogger(logger),
)import "log/slog"
driver := entslog.New(
sql.Open("mysql", dsn),
entslog.WithFilter(func(ctx context.Context, attrs ...slog.Attr) []slog.Attr {
filtered := make([]slog.Attr, 0, len(attrs))
for _, attr := range attrs {
// Filter out sensitive information like passwords
if attr.Key == "password" || attr.Key == "token" {
continue
}
filtered = append(filtered, attr)
}
return filtered
}),
)driver := entslog.New(
sql.Open("mysql", dsn),
entslog.WithTrace(func(ctx context.Context) string {
// Use your own trace ID generation logic
if traceID := getTraceIDFromContext(ctx); traceID != "" {
return traceID
}
return uuid.New().String()
}),
)func transactionExample(ctx context.Context, client *ent.Client) error {
// Start transaction (logs transaction start with trace ID)
tx, err := client.Tx(ctx)
if err != nil {
return err
}
// All operations within the transaction are logged with the same trace ID
if err := tx.User.Create().SetName("John").Exec(ctx); err != nil {
tx.Rollback()
return err
}
// Commit (logs commit with the same trace ID)
return tx.Commit()
}{
"time": "2024-01-01T12:00:00.000Z",
"level": "INFO",
"msg": "Query",
"database": "driver",
"query": "SELECT * FROM users WHERE id = ?",
"args": "[1]"
}
{
"time": "2024-01-01T12:00:01.000Z",
"level": "INFO",
"msg": "Tx started",
"database": "tx",
"id": "550e8400-e29b-41d4-a716-446655440000"
}
{
"time": "2024-01-01T12:00:02.000Z",
"level": "INFO",
"msg": "Exec",
"database": "tx",
"id": "550e8400-e29b-41d4-a716-446655440000",
"query": "INSERT INTO users (name) VALUES (?)",
"args": "[\"John\"]"
}
{
"time": "2024-01-01T12:00:03.000Z",
"level": "INFO",
"msg": "Commit",
"database": "tx",
"id": "550e8400-e29b-41d4-a716-446655440000"
}- Structured Logging: Uses Go 1.21's
log/slogfor structured, leveled logging - Transaction Tracing: Assigns unique trace IDs to transactions for complete operation tracking
- Configurable: Customize log levels, logger, filters, and trace generation
- Ent Compatible: Works seamlessly with ent's driver interface
- Production Ready: Efficient implementation with minimal overhead