Skip to content

yylego/kratos-trace

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

kratos-trace

Trace ID middleware with cross-service propagation using Kratos framework, providing request tracking and distributed tracing.


CHINESE README

中文说明

Main Features

  • 🔍 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() with log.With to auto-include trace ID in each log line

Installation

go get github.com/yylego/kratos-trace/tracekratos

Quick Start

package 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),
    // )
}

Advanced Usage

Custom Trace ID Generation

tracekratos.WithNewTraceID(func(ctx context.Context) string {
    return uuid.New().String()
})

Enable Response Logging

tracekratos.WithLogReply(true)

Custom Log Config

tracekratos.WithLogLevel(log.LevelDebug)

Custom Args Format

tracekratos.WithFormatArgs(func(req any) string {
    return fmt.Sprintf("%+v", req)
})

Auto Include Trace ID in Each Log Line

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=done

Get Trace ID in Business Code

func (s *Service) DoSomething(ctx context.Context) {
    traceID := tracekratos.GetTraceID(ctx)
    // or
    traceID := tracekratos.GetTraceIDFromContext(ctx)
}

Complete Examples

See kratos-trace-demos to view complete integration in Kratos projects:

API Reference

Config

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
}

Options

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 logging

Functions

func 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 string

📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

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

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

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! 🎉🎉🎉


GitHub Stars

Stargazers

About

Trace ID middleware with cross-service propagation using Kratos framework, providing request tracking and distributed tracing

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors