Comments (8)
🤖
Hello @dagehuifei,
Nice to meet you! I'm Dosu, a friendly bot, here to assist you with your questions, debugging, and contributing to Kratos. While we wait for a human maintainer, feel free to ask me anything related to your issue. I'm here to help you!
根据我在Kratos仓库中找到的相关问题,你可以通过以下方式解决你的问题:
-
你需要确保在你的中间件链中,
tracing.Server()
在logging.Server()
之前。这是因为tracing.Server()
会在请求上下文中设置trace.id,然后logging.Server()
可以从上下文中获取并打印它。这个解决方案可以在这个问题中找到:[Question] why trace_id and span_id in logger ctx? -
你可以创建一个自定义的中间件,该中间件可以从请求上下文中获取trace.id并将其打印出来。这个解决方案可以在这个问题中找到:[Question] trace.id is not passed。这里是修改后的代码:
package main
import (
"context"
"fmt"
"os"
"github.com/gin-gonic/gin"
kgin "github.com/go-kratos/gin"
"github.com/go-kratos/kratos/v2"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/middleware/logging"
"github.com/go-kratos/kratos/v2/middleware/recovery"
"github.com/go-kratos/kratos/v2/middleware/tracing"
"github.com/go-kratos/kratos/v2/transport"
"github.com/go-kratos/kratos/v2/transport/http"
"go.opentelemetry.io/otel"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
func customMiddleware(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
if tr, ok := transport.FromServerContext(ctx); ok {
fmt.Println("operation:", tr.Operation())
}
if c, ok := kgin.FromGinContext(ctx); ok {
c.Request = c.Request.WithContext(ctx)
}
reply, err = handler(ctx, req)
return
}
}
func main() {
router := gin.Default()
tp := sdktrace.NewTracerProvider()
otel.SetTracerProvider(tp)
logger := log.With(log.NewStdLogger(os.Stdout),
"ts", log.DefaultTimestamp,
"caller", log.DefaultCaller,
"trace.id", tracing.TraceID(),
"span.id", tracing.SpanID(),
)
log.SetLogger(logger)
// 使用kratos中间件
router.Use(kgin.Middlewares(recovery.Recovery(), tracing.Server(), logging.Server(logger), customMiddleware))
router.GET("/helloworld/:name", func(ctx *gin.Context) {
name := ctx.Param("name")
log.Context(ctx.Request.Context()).Info("hello world")
if name == "error" {
// 返回kratos error
kgin.Error(ctx, errors.Unauthorized("auth_error", "no authentication"))
} else {
ctx.JSON(200, map[string]string{"welcome": name})
}
})
httpSrv := http.NewServer(http.Address(":8000"))
httpSrv.HandlePrefix("/", router)
app := kratos.New(
kratos.Name("gin"),
kratos.Logger(logger),
kratos.Server(
httpSrv,
),
)
if err := app.Run(); err != nil {
panic(err)
}
}
希望这些信息能帮助你解决问题。如果你还有其他问题,欢迎继续提问。
Sources
- [Question] trace.id is not passed
- [Question] why trace_id and span_id in logger ctx?
- Logging middleware will be missing trace_id when logger is filterlogger
- transport/http/client.go
This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.
Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.
If you want to continue the conversation, start your reply with @dosu-bot.
from kratos.
Line 52 in 9adece0
Line 60 in 9adece0
from kratos.
🤖
Hello @dagehuifei,
Welcome to the Kratos repository! I'm Dosu, a friendly bot here to help with bug fixes, answer your questions, and guide you on your journey to being a contributor. While we wait for a human maintainer, I'll be assisting you with your issue.
I'm currently reviewing your log printing issue and will get back to you with an answer shortly. Stay tuned!
from kratos.
这几个issue都试过,但是还是没解决问题
from kratos.
Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑🤝🧑👫🧑🏿🤝🧑🏻👩🏾🤝👨🏿👬🏿
I have tried these issues, but still haven’t solved the problem.
from kratos.
https://github.com/go-kratos/examples/tree/main/traces
from kratos.
Please check your code based on the example to see if the middleware order is correct, if a trace provider is provided, and if the logger uses a non global logger
from kratos.
Tracing middleware can print trace.id , it's fine . how to print trace.id in service or biz ?
How to print trace.id in [https://github.com/go-kratos/examples/blob/main/traces/app/user/main.go:60] in the func (s *server) GetMyMessages(ctx context.Context, in *v1.GetMyMessagesRequest) (*v1.GetMyMessagesReply, error) func when the func add log like log.Infow("xxx", "xxx")
INFO trace_id= span_id= caller=user/main.go:64 ssssss=sssssssssss
Handle connection.
INFO trace_id=8a37f38477b1ff60d22abefffa565c56 span_id=5a48b5a5640b0027 caller=tracing/tracing.go:57 kind=server component=http operation=/api.user.v1.User/GetMyMessages args=count:1 code=0 reason= stack= latency=0.005574167
from kratos.
Related Issues (20)
- [Feature] consule register need suport tags[] HOT 2
- When the App stops, the ctx in the afterStop callback is not available HOT 3
- [Question] How to return other Status Code in a successful HTTP request? HOT 7
- [Feature] Add Unwrap to custom response writer. HOT 3
- [Proposal] config feature roadmap HOT 22
- [Feature] replace kratos metrics with otel metrics HOT 3
- [The modification of header file information of http response does not take effect] ctx.Header().Set("Content-Type", "application/octet-stream") HOT 5
- [Question] How to return a custom response json? HOT 1
- Package version dependency issue HOT 4
- go generate ./...failed HOT 5
- [Feature]Add svrType related fields in proto to protoc-gen-go-http and http transport HOT 3
- proto file used to build the api document reported an error HOT 1
- consul watch, the server is offline and will not receive any notification HOT 6
- [Feature] Add NewClient method to gRPC Client HOT 3
- [Question] DDD的最佳实践方式?包括CQRS、Clean Architecture、六边形结构 HOT 5
- [Question]请教下kratos如何定义支持上传文件接口? HOT 2
- metrics statistics and usage issues [Question] HOT 5
- `stream` response in proto failed to generate http client HOT 3
- [Feature] Add kratos errors to buf remote plugin HOT 1
- [Question] I modified it based on examples/helloworld and found that client/main.go reported an error when executing. I am not sure if it is a BUG. HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from kratos.