Ktor utilities library for JVM platform containing common utility functions, cryptographic operations, date handling, logging utilities, pipeline functionality, I/O adapters, encoding/decoding utilities, network address handling, and various platform-specific implementations for the Ktor framework.
—
Multi-level logging interface with lazy evaluation for performance optimization. Provides a flexible logging system with support for different log levels, structured logging, and platform-specific implementations.
Core logging interface providing multiple log levels with lazy evaluation support.
/**
* Multi-level logging interface (expect/actual pattern for multiplatform)
*/
expect interface Logger {
/** Log trace level message */
fun trace(message: String)
/** Log trace level message with exception */
fun trace(message: String, cause: Throwable)
/** Log debug level message */
fun debug(message: String)
/** Log debug level message with exception */
fun debug(message: String, cause: Throwable)
/** Log info level message */
fun info(message: String)
/** Log info level message with exception */
fun info(message: String, cause: Throwable)
/** Log warning level message */
fun warn(message: String)
/** Log warning level message with exception */
fun warn(message: String, cause: Throwable)
/** Log error level message */
fun error(message: String)
/** Log error level message with exception */
fun error(message: String, cause: Throwable)
}
/** Check if trace level is enabled */
expect val Logger.isTraceEnabled: Boolean
/** Check if debug level is enabled */
expect val Logger.isDebugEnabled: Boolean
/** Log error from exception using its message */
fun Logger.error(exception: Throwable)Usage Examples:
import io.ktor.util.logging.*
val logger = KtorSimpleLogger("MyApp")
// Basic logging
logger.info("Application started")
logger.warn("Configuration not found, using defaults")
// Lazy evaluation for expensive operations
logger.debug { "Processing user data: ${expensiveUserDataCalculation()}" }
logger.trace { "Request details: ${request.toDetailedString()}" }
// Error logging with exceptions
try {
riskyOperation()
} catch (e: Exception) {
logger.error("Operation failed", e)
logger.error(e) { "Additional context: ${context.details}" }
}Factory function for creating simple logger instances.
/**
* Create logger instance with name (expect/actual factory function)
* @param name Logger name (typically class or component name)
* @return Logger instance
*/
expect fun KtorSimpleLogger(name: String): LoggerUsage Examples:
import io.ktor.util.logging.*
// Create logger with default INFO level
val logger = KtorSimpleLogger("DatabaseService")
// Create logger with specific level
val debugLogger = KtorSimpleLogger("DebugComponent", LogLevel.DEBUG)
// Check if level is enabled before expensive operations
if (logger.isEnabled(LogLevel.DEBUG)) {
val debugInfo = collectDebugInformation()
logger.debug("Debug info: $debugInfo")
}
// Use different loggers for different components
class UserService {
private val logger = KtorSimpleLogger("UserService")
fun createUser(userData: UserData) {
logger.info("Creating user: ${userData.username}")
try {
// ... create user
logger.debug("User created successfully")
} catch (e: Exception) {
logger.error("Failed to create user", e)
throw e
}
}
}JVM-specific logger factory with integration for popular logging frameworks.
/**
* Factory for creating loggers on JVM platform
*/
object LoggerFactory {
/** Create logger with specified name */
fun getLogger(name: String): Logger
/** Create logger for specific class */
fun getLogger(clazz: Class<*>): Logger
/** Create logger with inline class reification */
inline fun <reified T> getLogger(): Logger
}Usage Examples:
import io.ktor.util.logging.*
// Create loggers using factory
val serviceLogger = LoggerFactory.getLogger("UserService")
val classLogger = LoggerFactory.getLogger(DatabaseService::class.java)
// Create logger with reified type
class PaymentProcessor {
private val logger = LoggerFactory.getLogger<PaymentProcessor>()
fun processPayment(amount: Double) {
logger.info("Processing payment: $amount")
// ... payment logic
}
}
// Use in companion objects
class OrderService {
companion object {
private val logger = LoggerFactory.getLogger<OrderService>()
}
fun createOrder() {
logger.debug("Creating new order")
}
}Enhanced logging capabilities with structured data support.
/**
* Structured logging with key-value pairs
*/
interface StructuredLogger : Logger {
/** Log with structured data */
fun info(message: String, vararg fields: Pair<String, Any?>)
fun debug(message: String, vararg fields: Pair<String, Any?>)
fun warn(message: String, vararg fields: Pair<String, Any?>)
fun error(message: String, exception: Throwable?, vararg fields: Pair<String, Any?>)
/** Create logger context with persistent fields */
fun withFields(vararg fields: Pair<String, Any?>): StructuredLogger
}
/**
* MDC (Mapped Diagnostic Context) utilities for request tracing
*/
object MDC {
/** Put value in diagnostic context */
fun put(key: String, value: String?)
/** Get value from diagnostic context */
fun get(key: String): String?
/** Remove value from diagnostic context */
fun remove(key: String)
/** Clear all diagnostic context */
fun clear()
/** Execute block with temporary MDC values */
fun <T> withContext(vararg pairs: Pair<String, String>, block: () -> T): T
}Usage Examples:
import io.ktor.util.logging.*
// Structured logging
val structuredLogger: StructuredLogger = // ... implementation
structuredLogger.info(
"User login successful",
"userId" to 12345,
"username" to "alice",
"loginMethod" to "oauth2"
)
structuredLogger.error(
"Payment processing failed",
exception,
"orderId" to order.id,
"amount" to order.total,
"currency" to order.currency
)
// Logger with persistent context
val userLogger = structuredLogger.withFields(
"userId" to currentUser.id,
"sessionId" to currentSession.id
)
userLogger.info("User action performed", "action" to "profile_update")
// MDC for request tracing
MDC.withContext(
"requestId" to UUID.randomUUID().toString(),
"userId" to user.id.toString()
) {
logger.info("Processing user request")
processUserRequest()
logger.info("Request processing complete")
}Asynchronous logging capabilities for high-performance scenarios.
/**
* Asynchronous logger wrapper
*/
class AsyncLogger(
private val delegate: Logger,
private val bufferSize: Int = 1000,
private val flushInterval: Duration = 1.seconds
) : Logger {
/** Start async logging */
fun start()
/** Stop async logging and flush remaining messages */
suspend fun stop()
/** Force flush of buffered messages */
suspend fun flush()
}
/**
* Batched logging for high-throughput scenarios
*/
class BatchLogger(
private val delegate: Logger,
private val batchSize: Int = 100
) : Logger {
/** Flush current batch */
fun flushBatch()
}Usage Examples:
import io.ktor.util.logging.*
import kotlinx.coroutines.*
// Async logging for high-performance applications
val baseLogger = KtorSimpleLogger("HighThroughputService")
val asyncLogger = AsyncLogger(baseLogger, bufferSize = 5000)
// Start async logging
asyncLogger.start()
// Log messages (buffered and written asynchronously)
repeat(10000) { i ->
asyncLogger.info("Processing item $i")
}
// Graceful shutdown
asyncLogger.stop()
// Batch logging for bulk operations
val batchLogger = BatchLogger(baseLogger, batchSize = 50)
repeat(1000) { i ->
batchLogger.debug("Batch item $i")
if (i % 50 == 0) {
batchLogger.flushBatch()
}
}Configuration utilities for logger setup and management.
/**
* Logger configuration builder
*/
class LoggerConfig {
/** Set default log level */
var defaultLevel: LogLevel = LogLevel.INFO
/** Set logger-specific levels */
fun level(loggerName: String, level: LogLevel)
/** Set output format */
var format: LogFormat = LogFormat.TEXT
/** Set output destination */
var output: LogOutput = LogOutput.CONSOLE
/** Apply configuration */
fun apply()
}
/**
* Log format options
*/
enum class LogFormat {
TEXT, JSON, STRUCTURED
}
/**
* Log output destinations
*/
enum class LogOutput {
CONSOLE, FILE, SYSLOG
}Usage Examples:
import io.ktor.util.logging.*
// Configure logging system
val config = LoggerConfig().apply {
defaultLevel = LogLevel.DEBUG
level("io.ktor.server", LogLevel.INFO)
level("io.ktor.client", LogLevel.WARN)
format = LogFormat.JSON
output = LogOutput.FILE
}
config.apply()
// Use configured loggers
val logger = LoggerFactory.getLogger("MyApplication")
logger.debug("This will be logged based on configuration")isEnabled() before expensive operationsAsyncLogger for high-throughput scenariosInstall with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-utils-jvm