Git Product home page Git Product logo

Comments (8)

dosubot avatar dosubot commented on May 29, 2024 4

🤖

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仓库中找到的相关问题,你可以通过以下方式解决你的问题:

  1. 你需要确保在你的中间件链中,tracing.Server()logging.Server()之前。这是因为tracing.Server()会在请求上下文中设置trace.id,然后logging.Server()可以从上下文中获取并打印它。这个解决方案可以在这个问题中找到:[Question] why trace_id and span_id in logger ctx?

  2. 你可以创建一个自定义的中间件,该中间件可以从请求上下文中获取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


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.

shenqidebaozi avatar shenqidebaozi commented on May 29, 2024 1

func WithContext(ctx context.Context, l Logger) Logger {

func (h *Helper) WithContext(ctx context.Context) *Helper {

from kratos.

dosubot avatar dosubot commented on May 29, 2024

🤖

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.

dagehuifei avatar dagehuifei commented on May 29, 2024

这几个issue都试过,但是还是没解决问题

from kratos.

kratos-ci-bot avatar kratos-ci-bot commented on May 29, 2024

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.

shenqidebaozi avatar shenqidebaozi commented on May 29, 2024

https://github.com/go-kratos/examples/tree/main/traces

from kratos.

shenqidebaozi avatar shenqidebaozi commented on May 29, 2024

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.

dagehuifei avatar dagehuifei commented on May 29, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.