Trace ID middleware with cross-service propagation using Kratos framework, providing request tracking and distributed tracing.
- 🔍 Trace ID Logging - Show trace ID in request logs
- 🔗 Cross-Service Propagation - Auto inject trace ID into outgoing gRPC metadata for downstream services
- 🚀 Auto Generation - Auto generate trace ID when not provided
- ⚙️ Flexible Config - Build config with custom options
- 📊 Response Logging - Response and cost logging on demand
- 🎯 Context Access - Get trace ID from context in business code
- 📝 Log Integration - Use
LogTraceID()withlog.Withto auto-include trace ID in each log line
go get github.com/yylego/kratos-trace/tracekratospackage main
import (
"context"
"github.com/go-kratos/kratos/v2/log"
"github.com/google/uuid"
"github.com/yylego/kratos-trace/tracekratos"
)
func main() {
// Create trace config with all options
config := tracekratos.NewConfig("X-Trace-ID",
tracekratos.WithLogLevel(log.LevelDebug),
tracekratos.WithLogReply(true),
tracekratos.WithNewTraceID(func(ctx context.Context) string {
return uuid.New().String()
}),
tracekratos.WithFormatArgs(func(req any) string {
return fmt.Sprintf("%+v", req)
}),
)
// Create trace middleware
middleware := tracekratos.NewTraceMiddleware(config, log.DefaultLogger)
// Use in Kratos server
// httpSrv := http.NewServer(
// http.Middleware(middleware),
// )
}tracekratos.WithNewTraceID(func(ctx context.Context) string {
return uuid.New().String()
})tracekratos.WithLogReply(true)tracekratos.WithLogLevel(log.LevelDebug)tracekratos.WithFormatArgs(func(req any) string {
return fmt.Sprintf("%+v", req)
})Use LogTraceID() with log.With to auto-include trace ID in each log line. No need to pass trace ID in business code — each log statement within the same request context will contain the trace ID.
// Wrap the base Kratos log.Logger with LogTraceID valuer
logger = log.With(logger, "request-trace", tracekratos.LogTraceID())
// Now each log line within a request will auto-include trace ID:
// INFO request-trace=ABC-123-XYZ-456 msg=processing
// INFO request-trace=ABC-123-XYZ-456 msg=donefunc (s *Service) DoSomething(ctx context.Context) {
traceID := tracekratos.GetTraceID(ctx)
// or
traceID := tracekratos.GetTraceIDFromContext(ctx)
}See kratos-trace-demos to view complete integration in Kratos projects:
- demo1kratos - Basic integration with HTTP and gRPC
- demo2kratos - Advanced usage with Wire DI
Config struct to trace middleware.
type Config struct {
TraceKeyName string // HTTP head name to get trace ID
NewTraceID func(context.Context) string // Generate new trace ID
FormatArgs func(req any) string // Format request args
LogLevel log.Level // Log config
LogReply bool // Log response and cost
}func WithLogLevel(level log.Level) Option // Set log config
func WithNewTraceID(fn func(context.Context) string) Option // Set custom trace ID creation function
func WithFormatArgs(fn func(req any) string) Option // Set custom args format function
func WithLogReply(enable bool) Option // Enable response and cost loggingfunc NewConfig(keyName string, opts ...Option) *Config // Create config with trace name and options
func NewTraceMiddleware(config *Config, logger log.Logger) middleware.Middleware // Create trace middleware
func LogTraceID() log.Valuer // Returns log.Valuer to auto-include trace ID in each log line
func GetTraceID(ctx context.Context) string // Get trace ID from context (short name)
func GetTraceIDFromContext(ctx context.Context) string // Get trace ID from context
func ExtractArgs(req any) string // Extract request args to stringMIT License - see LICENSE.
Contributions are welcome! Report bugs, suggest features, and contribute code:
- 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
- 💡 Fresh ideas? Create an issue to discuss
- 📖 Documentation confusing? Report it so we can improve
- 🚀 Need new features? Share the use cases to help us understand requirements
- ⚡ Performance issue? Help us optimize through reporting slow operations
- 🔧 Configuration problem? Ask questions about complex setups
- 📢 Follow project progress? Watch the repo to get new releases and features
- 🌟 Success stories? Share how this package improved the workflow
- 💬 Feedback? We welcome suggestions and comments
New code contributions, follow this process:
- Fork: Fork the repo on GitHub (using the webpage UI).
- Clone: Clone the forked project (
git clone https://github.com/yourname/repo-name.git). - Navigate: Navigate to the cloned project (
cd repo-name) - Branch: Create a feature branch (
git checkout -b feature/xxx). - Code: Implement the changes with comprehensive tests
- Testing: (Golang project) Ensure tests pass (
go test ./...) and follow Go code style conventions - Documentation: Update documentation to support client-facing changes
- Stage: Stage changes (
git add .) - Commit: Commit changes (
git commit -m "Add feature xxx") ensuring backward compatible code - Push: Push to the branch (
git push origin feature/xxx). - PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.
Please ensure tests pass and include relevant documentation updates.
Welcome to contribute to this project via submitting merge requests and reporting issues.
Project Support:
- ⭐ Give GitHub stars if this project helps you
- 🤝 Share with teammates and (golang) programming friends
- 📝 Write tech blogs about development tools and workflows - we provide content writing support
- 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene
Have Fun Coding with this package! 🎉🎉🎉