Coder Social home page Coder Social logo

ktor-features-zipkin's Introduction

Ktor: ZipkinIds feature

Build and Publish Maven Central

A Ktor installable plugin (formerly called feature) for particiapting in Zipkin distributed tracing.

Why might you want this?

You are building microservices in Ktor and want to instrument them for tracing using Zipkin.

What does it do?

Incoming headers

The feature reads incoming HTTP tracing headers, either multiple headers:

  • X-B3-TraceId
  • X-B3-SpanId
  • X-B3-ParentSpanId
  • X-B3-Sampled or X-B3-Flags

or a single b3 header. See zipkin-b3-propagation for details.

Initiating tracing

The feature initiates tracing if configured, optionally only for specified paths.

Response headers

The feature returns tracing headers in the response that match those received or initiated.

Client requests

The feature propagates tracing into downstream client requests where installed into Ktor clients.

Logging MDC items

Optionally you can install the current tracing information into Slf4j mapped diagnostic context (MDC).

How do you use it?

There are two parts: a server feature and a client feature.

Server feature

An example is:

fun Application.module() {

    install(ZipkinIds) {
        initiateTracePathPrefixes = arrayOf("/api")
        b3Header = true
    }

    // Other feature installations

    routing {
        get("/health") {
            call.respond(mapOf("status" to "UP"))
        }

        post("/api/v1/service") {
            try {
                val message = call.receive<Message>()
                val result = call.processMessage(message)
                call.respond(HttpStatusCode.OK, result)
            } catch (e: Exception) {
                call.respond(HttpStatusCode.BadRequest, e.message ?: "There was an error processing your request")
            }
        }
    }
}

In this example, the feature is installed so it will initiate tracing only for requests starting with "/api".

  • Requests to /health without any tracing headers do not initiate tracing.
  • Requests to /api/v1/service without tracing headers initiate tracing.
  • Tracing initiated by the service respond with b3 headers and use them in client calls.
  • If requests contain tracing headers, those headers and their type (either b3 or X-B3-*) will be maintained.
  • Tracing information is stored in the ApplicationCall instance.

Client feature

To propagate tracing information into client calls, define extension functions on ApplicationCall, for example:

suspend fun ApplicationCall.processMessage(message: Message) {

    val url = "https://provider.com/api/v1/other-service"
    try {
        val client = HttpClient(CIO) {
            tracingParts?.let { it ->
                install(ClientIds) {
                    tracingParts = it
                }
            }
        }
        val response = client.post<String>(url) {
            body = TextContent(
                json.writeValueAsString(OutgoingMessage(message)),
                contentType = ContentType.Application.Json
            )
        }
    } catch (e: Exception) {
        logger.error("Client request failure", e)
    }
}

In this example:

  • When the client is being constructed, if the ApplicationCall contains a tracingParts attribute, install the ClientIds feature with that attribute.

Logging MDC

Install the keys into logging MDC in the application as part of call logging:

    install(CallLogging) {
        level = Level.INFO
        zipkinMdc()
        filter { call -> call.request.path().startsWith("/") }
    }

Keys available are:

  • b3Id
  • traceId
  • spanId
  • parentSpanId

They can be set in logback.xml like so:

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] [%X{b3Id}] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

Gradle dependency

repositories {
    // ...
    maven { url 'https://kotlin.bintray.com/ktor' }
    mavenCentral()
}

dependencies {
    // ...
    implementation 'com.michaelstrasser:ktor-features-zipkin:0.2.12'
}

ktor-features-zipkin's People

Contributors

mjstrasser avatar tw-mstrass avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

ktor-features-zipkin's Issues

Where is this library released?

Thank you for maintaining this awesome library. But when I import it to my project gradle can not find it:

Could not find com.michaelstrasser:ktor-features-zipkin:0.2.5.

My repositories is:

repositories {
    mavenLocal()
    jcenter()
    maven { url 'https://kotlin.bintray.com/ktor' }
}

Publish artifact to Maven Central

Hi, does it possible to publish your library to maven central? I can do it or help you to do it if you are not against.

We are just started to use your library in our project and unfortunately our policies does not allow us to use third party repositories.

Thanks in advance!

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.