Giter Club home page Giter Club logo

ktor-opentracing's Introduction

Maven Central GitHub Unit Tests Actions Status

Ktor OpenTracing Instrumentation

Library of Ktor features for OpenTracing instrumentation of HTTP servers and clients.

Usage

Server Spans

Install the OpenTracingServer feature as follows in a module:

install(OpenTracingServer)

The feature uses the tracer registered in GlobalTracer, which uses the ThreadContextElementScopeManager. This is needed to propagate the tracing context in the coroutine context of the calls. For example, you can instantiate and register a Jaeger tracer in the module before the call to install as follows:

val tracer: Tracer = config.tracerBuilder
    .withScopeManager(ThreadContextElementScopeManager())
    .build()

GlobalTracer.registerIfAbsent(tracer)

At this stage, the application will be creating a single span for the duration of the request. If the incoming request has tracing context in its HTTP headers, then the span will be a child of the one in that context. Otherwise, the feature will start a new trace.

Individual code blocks

To get a more detailed view of requests, we might want to instrument individual code blocks as child spans. We could start a new child span using the tracer instance directly, however this would be too intrusive and verbose. Instead, we can use the span inline function as follows.

class UserRepository {
    fun getUser(id: UUID): User = span("<operation-name>") {
        setTag("UserId", id)
    
        ... database call ...
       
        return user
    }
}

span is passed an operation name and an anonymous lambda, which has the Span as a receiver object. This means that you can call setTag, log, getBaggageItem (or any method on the Span interface).

Concurrency with async

Concurrent operations using async can break in-process context propagation which uses coroutine context, leading to spans with incorrect parents. To solve this issue, replace the calls to async with asyncTraced. This will pass the correct tracing context to the new coroutines.

val scrapeResults = urls.map { url -> 
    asyncTraced { 
        httpClient.get(url)
    }
    .awaitAll()
}

Underneath the hood, asyncTraced is adding the current tracing context to the coroutine context using a call to tracingContext(). You can add it yourself by calling async(tracingContext()). To launch a new coroutine with the tracing context, call launchTraced.

Client Spans

If your application calls another service using the Ktor HTTP client, you can install the OpenTracingClient feature on the client to create client spans:

install(OpenTracingClient)

The outgoing HTTP headers from this client will contain the trace context of the client span. This allows the service that is called to create child spans of this client span.

We recommend using this feature in a server that has OpenTracingServer installed.

Configuration

Filter Requests

Your application might be serving static content (such as k8s probes), for which you do not to create traces. You can filter these out as follows:

install(OpenTracingServer) {
    filter { call -> call.request.path().startsWith("/_probes") }
}

Tag Spans

It is also possible to configure tags to be added to each span in a trace. For example to add the thread name and a correlation id:

install(OpenTracingServer) {
    addTag("threadName") { Thread.currentThread().name }
    addTag("correlationId") { MDC.get("correlationId") }
}

Installation

From Maven Central.

Maven

Add the following dependency to your pom.xml:

<dependency>
 <groupId>com.zopa</groupId>
 <artifactId>ktor-opentracing</artifactId>
 <version>VERSION_NUMBER</version>
</dependency>

Gradle

Add the following to your dependencies in your build.gradle

implementation "com.zopa:ktor-opentracing:VERSION_NUMBER"

Examples

Related Projects

ktor-opentracing's People

Contributors

aideencostello avatar fstien avatar hj1611 avatar tobiasmuehl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ktor-opentracing's Issues

Possible problem with `StatusPages` feature and error responses ?

Hi,

I'm using version 0.3.6 and everything works correctly for responses that are not in error. However, when I have an exception on my backend, no root span is created by the OpenTracingServer feature. It seems to be linked with the use of the StatusPages feature.

For ex. if I have the StatusPages feature installed with this configuration :

install(StatusPages) {
    exception<Throwable> { cause ->
        call.respond(HttpStatusCode.InternalServerError)
    }
}

and throw an exception in a get mapping :

get("test") {
    throw IllegalArgumentException()
}

-> then no span is created.

And if I uninstall the StatusPages feature and modify my mapping to do :

get("test") {
    call.respond(HttpStatusCode.InternalServerError)
}

-> then a span is created as expected.

I think it is linked to phases but I know very little on the topic so....

Thanks

Tracing phase should surround call logging

Hi there, it's me again :)

I integrated your library successfully and for the "normal use case" everything is fine. However, we have the following requirement: Our service has to include trace ids in all log statements coming from the service.

I have a Layout implementation for logback and everything works fine for regular logging - I just use GlobalTracer.get().activeSpan() in the Layout and fine. However, when the CallLogging is done (Ktor included feature), the span/trace is already closed. That's likely because the finishTracingPhase is happening before the call logging is done.

Is there any chance we can have the span (given by an external trace id through the request) active until the CallLogging phase is done?

My current workaround is to evaluate the MDC in case there is no active span, and the MDC is populated in an early phase manually. That works, but it's not the nicest thing I ever implemented :)

Thank you in advance!

Missing context request headers shouldn't create `info` level logs

At least in our use case, it's fairly common that the request will not contain the headers required for context propagation and this info log creates quite a bit of unnecessary spam in the log for each request: https://github.com/zopaUK/ktor-opentracing/blob/3cf825cdd1262c86642d624b9c2feb946d5029d8/src/main/kotlin/com/zopa/ktor/opentracing/OpenTracingServer.kt#L63

We can configure the log level for the com.zopa.ktor.opentracing.Utils logger as warn as a workaround, but it makes more sense to me for this to be a debug or even trace-level message

Advice on when/how to insert trace-id into logging context?

Hello! Thanks a lot for this library!

I would like to use MDC.put to put the trace-id into the logging context so that it gets included in all logs. But when I should do that? I guess I would need to define my own phase and insert it between Features and OpenTracingStart. Or? Thank you!

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.