Skip to content

Instantly share code, notes, and snippets.

@bobisme
Last active April 22, 2020 21:54
Show Gist options
  • Save bobisme/498c38127d2da0da894e41f9489541ac to your computer and use it in GitHub Desktop.
Save bobisme/498c38127d2da0da894e41f9489541ac to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"time"
"github.com/opentracing/opentracing-go"
otlog "github.com/opentracing/opentracing-go/log"
"github.com/rs/zerolog/log"
jaeger "github.com/uber/jaeger-client-go"
config "github.com/uber/jaeger-client-go/config"
"github.com/valyala/fasthttp"
)
var (
listenAddr = "127.0.0.1:8080"
)
func instrument(service string) (opentracing.Tracer, io.Closer) {
cfg := &config.Configuration{
Sampler: &config.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
},
}
tracer, closer, err := cfg.New(service, config.Logger(jaeger.StdLogger))
if err != nil {
panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err))
}
opentracing.SetGlobalTracer(tracer)
return tracer, closer
}
func requestHandler(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}
func loggingMiddleware(req fasthttp.RequestHandler) fasthttp.RequestHandler {
return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
begin := time.Now()
req(ctx)
end := time.Now()
log.Info().
Bytes("method", ctx.Method()).
Str("remoteAddr", ctx.RemoteAddr().String()).
IPAddr("remoteIP", ctx.RemoteIP()).
Int("status", ctx.Response.Header.StatusCode()).
Bytes("uri", ctx.RequestURI()).
Bytes("userAgent", ctx.UserAgent()).
Dur("latency", end.Sub(begin)).
Msg("request")
})
}
func tracingMiddleware(req fasthttp.RequestHandler) fasthttp.RequestHandler {
return fasthttp.RequestHandler(func(reqCtx *fasthttp.RequestCtx) {
span, _ := opentracing.StartSpanFromContext(reqCtx, string(reqCtx.RequestURI()))
defer span.Finish()
span.LogFields(
otlog.String("event", "request"),
otlog.Int("status", reqCtx.Response.Header.StatusCode()),
)
})
}
func main() {
_, closer := instrument("blah-app")
defer closer.Close()
handler := loggingMiddleware(tracingMiddleware(requestHandler))
if err := fasthttp.ListenAndServe(listenAddr, handler); err != nil {
log.Fatal().Str("listenAddr", listenAddr).Err(err).Msg("error listening")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment