/

Metadata & Context

Add rich contextual information to your logs for better debugging and analysis. Use metadata and context to provide structured data alongside your log messages.

Adding Context to Logs

Using Fluent API

Java
Log.withContext("userId", "12345")
   .withContext("sessionId", "sess-abc")
   .info("User performed action");

Using Direct API

Java
import java.util.Map;

Map<String, Object> context = Map.of(
    "orderId", "ORD-123",
    "amount", 99.99,
    "currency", "USD"
);

Log.info("Order created", null, context);

Adding Metadata

Java
Log.withMetadata("executionTimeMs", 1250)
   .withMetadata("responseCode", 200)
   .info("API call completed");

Combining Context and Metadata

Java
Log.withMetadata("executionTimeMs", 450)
   .withContext("endpoint", "/api/orders")
   .withContext("method", "POST")
   .withTags("api", "performance")
   .info("API request processed");

Global Meta Context

Add application-wide context that is included in all subsequent logs:

Java
Log.addMetaContext("environment", "production");
Log.addMetaContext("version", "1.0.0");
Log.addMetaContext("region", "us-east-1");

// All logs now include this global context
Log.info("Application started");

Practical Examples

Request Logging

Java
public void handleRequest(String requestId, String userId) {
    Log.withContext("requestId", requestId)
       .withContext("userId", userId)
       .withContext("timestamp", System.currentTimeMillis())
       .info("Request received");
}

Database Operation Logging

Java
public List<Order> findOrders(String customerId) {
    long startTime = System.currentTimeMillis();
    
    List<Order> orders = repository.findByCustomerId(customerId);
    
    Log.withContext("customerId", customerId)
       .withContext("resultCount", orders.size())
       .withMetadata("queryTimeMs", System.currentTimeMillis() - startTime)
       .withTags("database", "query")
       .info("Orders retrieved");
    
    return orders;
}

Best Practices

Context Best Practices

  • Use structured context instead of string concatenation
  • Include relevant context only to avoid log bloat
  • Use global meta context for application-wide information
  • Combine with tags for better filterability

Next Steps

Previous
Duplicate Suppression