☕ Java Integration Guide

Learn how to integrate the official TraceKit Java SDK into your applications for distributed tracing, code monitoring, and security scanning.

Official TraceKit Java SDK!

Use our production-ready SDK for Spring Boot and vanilla Java applications. Features include automatic tracing, security scanning, and local UI auto-detection.

📚 View on GitHub
📋

Prerequisites

  • • Java 8 or higher (Java 11+ recommended)
  • • An active TraceKit account
  • • A generated API key from the API Keys page

🔍 What Gets Traced Automatically?

With the Java Agent, these operations are traced automatically with ZERO code changes:

ComponentSetupAuto-Traced?
HTTP EndpointsJava Agent (zero code)✓ Yes
JDBC QueriesJava Agent (zero code)✓ Yes
HTTP Client CallsJava Agent (zero code)✓ Yes
Spring BootJava Agent (zero code)✓ Yes
Kafka/RabbitMQJava Agent (zero code)✓ Yes
Custom Business LogicManual spans (optional)Manual

📦 Installation

Spring Boot (Recommended)

Add the Spring Boot starter dependency:

<dependency>
    <groupId>dev.tracekit</groupId>
    <artifactId>tracekit-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

Or with Gradle:

implementation 'dev.tracekit:tracekit-spring-boot-starter:1.3.1'

Vanilla Java

Add the core SDK dependency:

<dependency>
    <groupId>dev.tracekit</groupId>
    <artifactId>tracekit-core</artifactId>
    <version>1.3.1</version>
</dependency>

Or with Gradle:

implementation 'dev.tracekit:tracekit-core:1.3.1'

⚙️ Basic Setup

Spring Boot Configuration

Configure in application.yml:

tracekit:
  enabled: true
  api-key: ${TRACEKIT_API_KEY}
  service-name: my-service
  environment: production
  endpoint: { appURL }/v1/traces
  enable-code-monitoring: true  # Enables snapshot capture with security scanning

Auto-Configuration!

The SDK auto-configures and starts tracing automatically. Spring Boot controllers, database queries, and HTTP clients are traced with zero code changes.

Vanilla Java Initialization

Initialize the SDK programmatically:

import dev.tracekit.TracekitSDK;
import dev.tracekit.TracekitConfig;

public class Application {
    public static void main(String[] args) {
        // Initialize SDK
        TracekitConfig config = TracekitConfig.builder()
            .apiKey(System.getenv("TRACEKIT_API_KEY"))
            .serviceName("my-service")
            .environment("production")
            .endpoint("{ appURL }/v1/traces")
            .enableCodeMonitoring(true)
            .build();

        TracekitSDK sdk = TracekitSDK.create(config);

        // Your application code here...

        // Shutdown on application exit
        Runtime.getRuntime().addShutdownHook(new Thread(sdk::shutdown));
    }
}

🚀 Framework Integration

The TraceKit SDK automatically instruments popular frameworks with zero code changes.

Spring Boot Example

Your existing Spring Boot controllers are automatically traced:

// Your existing Spring Boot application - NO CHANGES NEEDED!
@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping("/users")
    public List<User> getUsers() {
        // This endpoint is automatically traced!
        return userService.findAll();
    }

    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        // This endpoint is also automatically traced!
        return userService.save(user);
    }
}

// Just add the dependency and configure - everything is traced automatically!

🔒 Code Monitoring & Security Scanning

Enable code monitoring to capture snapshots with automatic security scanning. The SDK detects and redacts sensitive information (PII, credentials, API keys) automatically.

// Code monitoring is enabled via configuration
tracekit:
  enable-code-monitoring: true

// Use captureSnapshot() to capture variable state with security scanning
import dev.tracekit.TracekitSDK;

public class OrderService {
    private final TracekitSDK tracekit;

    public void processOrder(Order order) {
        // Capture snapshot with automatic security scanning
        tracekit.captureSnapshot("order_processing",
            Map.of(
                "orderId", order.getId(),
                "customerId", order.getCustomerId(),
                "total", order.getTotal()
            )
        );

        // Process order...
    }
}
🔐

Automatic Security Scanning

Sensitive data is automatically detected and redacted before sending to the backend. This includes email addresses, phone numbers, SSNs, credit cards, API keys, passwords, and private keys.

🔧 Manual Instrumentation (Optional)

For custom business logic not automatically traced, you can manually create spans using the OpenTelemetry API:

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;

public class OrderService {
    private static final Tracer tracer =
        GlobalOpenTelemetry.getTracer("order-service");

    public void processOrder(String orderId) {
        // Start a parent span
        Span span = tracer.spanBuilder("process_order")
            .setAttribute("order.id", orderId)
            .startSpan();

        try (Scope scope = span.makeCurrent()) {
            // Child spans automatically link to parent
            validateOrder(orderId);
            chargePayment(orderId);

            span.setAttribute("order.status", "completed");
        } finally {
            span.end();
        }
    }

    private void validateOrder(String orderId) {
        Span span = tracer.spanBuilder("validate_order")
            .setAttribute("order.id", orderId)
            .startSpan();
        try (Scope scope = span.makeCurrent()) {
            // Validation logic here
        } finally {
            span.end();
        }
    }
}

🔐 Environment Variables

Best practice: Store sensitive configuration in environment variables:

# .env or environment variables
TRACEKIT_API_KEY=ctxio_your_generated_api_key_here
OTEL_SERVICE_NAME=my-java-app
OTEL_EXPORTER_OTLP_ENDPOINT={ appURL }/v1/traces

🏭 Production Configuration

⚠️

Production Checklist

  • • Use HTTPS/TLS for the OTLP endpoint
  • • Store API keys in a secrets manager (AWS Secrets Manager, HashiCorp Vault)
  • • Set appropriate service names and versions
  • • Configure resource attributes (deployment.environment, host.name, etc.)
  • • Adjust sampling rates if needed for high-traffic services
  • • Monitor Java Agent overhead (typically <5%)

🔧 Troubleshooting

Traces Not Appearing?

  1. Verify your API key is correct and not revoked
  2. Check the endpoint URL matches your TraceKit instance
  3. Ensure the Java Agent is loaded (check startup logs)
  4. Verify the -javaagent parameter is before -jar
  5. Check application logs for OpenTelemetry errors

Complete Example

Here's a complete working Spring Boot example:

// Complete Spring Boot example with TraceKit SDK

// pom.xml
<dependency>
    <groupId>dev.tracekit</groupId>
    <artifactId>tracekit-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

// application.yml
tracekit:
  enabled: true
  api-key: ${TRACEKIT_API_KEY}
  service-name: spring-api
  environment: production
  enable-code-monitoring: true

// Application.java
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// UserController.java - automatically traced!
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    public List<User> getUsers() {
        // Automatically traced - no code changes needed!
        return userRepository.findAll();
    }

    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        // Automatically traced - no code changes needed!
        return userRepository.save(user);
    }
}

// That's it! Run normally: mvn spring-boot:run
🎉

You're all set!

Your Java application is now sending traces to TraceKit. Visit the Dashboard to see your traces.

Custom Metrics

Track custom metrics like request counts, queue sizes, and response times using the TraceKit metrics API.

Counter

Track monotonically increasing values (requests, events):

import dev.tracekit.TracekitSDK;
import dev.tracekit.metrics.Counter;
import java.util.Map;

// Get the SDK (injected in Spring Boot or created manually)
TracekitSDK sdk = ...;

// Create a counter with optional tags
Counter counter = sdk.counter("http.requests.total",
    Map.of("service", "api"));

// Increment by 1
counter.inc();

// Add a specific value
counter.add(5.0);

Gauge

Track values that can go up or down (queue size, connections):

import dev.tracekit.metrics.Gauge;

// Create a gauge
Gauge gauge = sdk.gauge("http.connections.active", Map.of());

// Set to specific value
gauge.set(42.0);

// Increment/decrement
gauge.inc();
gauge.dec();

Histogram

Track value distributions (latencies, sizes):

import dev.tracekit.metrics.Histogram;

// Create a histogram with tags
Histogram histogram = sdk.histogram("http.request.duration",
    Map.of("unit", "ms"));

// Record values
histogram.record(45.2);
histogram.record(123.5);

🚀 Next Steps

  • Explore your traces on the Traces page to identify performance bottlenecks
  • Optionally add custom spans for specific business logic you want to measure
  • Configure sampling for high-traffic services to reduce overhead
  • Set up alert rules to get notified when issues occur