Ktor HTTP client logging plugin for JavaScript targets providing comprehensive request/response logging capabilities with configurable levels, formats, and header sanitization
npx @tessl/cli install tessl/maven-io-ktor--ktor-client-logging-js@3.2.00
# Ktor Client Logging Plugin
1
2
Ktor Client Logging Plugin provides comprehensive HTTP request and response logging capabilities for Ktor HTTP client applications targeting JavaScript environments. It offers configurable logging levels, multiple output formats, header sanitization, and platform-specific logger implementations optimized for browser and Node.js environments.
3
4
## Package Information
5
6
- **Package Name**: ktor-client-logging-js
7
- **Package Type**: maven
8
- **Language**: Kotlin (JavaScript targets)
9
- **Installation**: `implementation("io.ktor:ktor-client-logging-js:3.2.0")`
10
11
## Core Imports
12
13
```kotlin
14
import io.ktor.client.plugins.logging.*
15
```
16
17
For HttpClient configuration:
18
19
```kotlin
20
import io.ktor.client.*
21
import io.ktor.client.plugins.logging.*
22
```
23
24
## Basic Usage
25
26
```kotlin
27
import io.ktor.client.*
28
import io.ktor.client.plugins.logging.*
29
30
// Basic setup with default configuration
31
val client = HttpClient {
32
install(Logging)
33
}
34
35
// Configured setup
36
val client = HttpClient {
37
install(Logging) {
38
level = LogLevel.ALL
39
logger = Logger.SIMPLE
40
}
41
}
42
43
// Advanced configuration
44
val client = HttpClient {
45
install(Logging) {
46
level = LogLevel.HEADERS
47
format = LoggingFormat.OkHttp
48
logger = Logger.DEFAULT
49
50
// Filter requests
51
filter { request ->
52
request.url.host == "api.example.com"
53
}
54
55
// Sanitize sensitive headers
56
sanitizeHeader { header ->
57
header == "Authorization"
58
}
59
}
60
}
61
```
62
63
## Capabilities
64
65
### Plugin Installation and Configuration
66
67
Install and configure the logging plugin for HTTP clients.
68
69
```kotlin { .api }
70
/**
71
* Main logging plugin that provides HTTP call logging capabilities
72
*/
73
val Logging: ClientPlugin<LoggingConfig>
74
75
/**
76
* Convenience function to configure and install the Logging plugin
77
*/
78
fun HttpClientConfig<*>.Logging(block: LoggingConfig.() -> Unit = {})
79
80
/**
81
* Configuration for the Logging plugin
82
*/
83
@KtorDsl
84
class LoggingConfig {
85
/** General format for logging requests and responses */
86
var format: LoggingFormat
87
88
/** Logger instance for output */
89
var logger: Logger
90
91
/** Logging level controlling what gets logged */
92
var level: LogLevel
93
94
/** Add a filter predicate for conditional logging */
95
fun filter(predicate: (HttpRequestBuilder) -> Boolean)
96
97
/** Sanitize sensitive headers to avoid values appearing in logs */
98
fun sanitizeHeader(placeholder: String = "***", predicate: (String) -> Boolean)
99
}
100
```
101
102
### Log Levels
103
104
Control the amount of information logged for HTTP requests and responses.
105
106
```kotlin { .api }
107
/**
108
* Logging level enumeration with boolean properties
109
*/
110
enum class LogLevel(
111
val info: Boolean,
112
val headers: Boolean,
113
val body: Boolean
114
) {
115
/** Log everything: info, headers, and body */
116
ALL(true, true, true),
117
118
/** Log info and headers, but not body */
119
HEADERS(true, true, false),
120
121
/** Log info and body, but not headers */
122
BODY(true, false, true),
123
124
/** Log only basic request/response info */
125
INFO(true, false, false),
126
127
/** No logging */
128
NONE(false, false, false)
129
}
130
```
131
132
### Logging Formats
133
134
Choose between different output formats for logged messages.
135
136
```kotlin { .api }
137
/**
138
* Output format for logged messages
139
*/
140
enum class LoggingFormat {
141
/** Standard Ktor logging format */
142
Default,
143
144
/**
145
* OkHttp-compatible logging format for application-level logs
146
* Writes only application-level logs because low-level HTTP communication
147
* is hidden within engine implementations
148
*/
149
OkHttp
150
}
151
```
152
153
### Logger Interface and Implementations
154
155
Core logging interface and built-in implementations for different environments.
156
157
```kotlin { .api }
158
/**
159
* Core logging interface for HTTP client
160
*/
161
interface Logger {
162
/** Add message to log */
163
fun log(message: String)
164
165
companion object
166
}
167
168
/** Default logger for JS/WASM platforms (delegates to SIMPLE) */
169
val Logger.Companion.DEFAULT: Logger
170
171
/** Simple logger using println with "HttpClient:" prefix */
172
val Logger.Companion.SIMPLE: Logger
173
174
/** Empty logger for testing (no-op implementation) */
175
val Logger.Companion.EMPTY: Logger
176
```
177
178
**Usage Examples:**
179
180
```kotlin
181
// Using default logger
182
val client = HttpClient {
183
install(Logging) {
184
logger = Logger.DEFAULT
185
}
186
}
187
188
// Using simple console logger
189
val client = HttpClient {
190
install(Logging) {
191
logger = Logger.SIMPLE
192
}
193
}
194
195
// Using empty logger for tests
196
val client = HttpClient {
197
install(Logging) {
198
logger = Logger.EMPTY
199
}
200
}
201
202
// Custom logger implementation
203
val customLogger = object : Logger {
204
override fun log(message: String) {
205
console.log("MyApp HTTP: $message")
206
}
207
}
208
209
val client = HttpClient {
210
install(Logging) {
211
logger = customLogger
212
}
213
}
214
```
215
216
### Request and Response Filtering
217
218
Control which HTTP calls get logged using predicate functions.
219
220
```kotlin { .api }
221
/**
222
* Add a filter predicate for conditional logging
223
* @param predicate Function that returns true if the request should be logged
224
*/
225
fun LoggingConfig.filter(predicate: (HttpRequestBuilder) -> Boolean)
226
```
227
228
**Usage Examples:**
229
230
```kotlin
231
val client = HttpClient {
232
install(Logging) {
233
// Only log API calls
234
filter { request ->
235
request.url.host.contains("api")
236
}
237
238
// Only log POST requests
239
filter { request ->
240
request.method == HttpMethod.Post
241
}
242
243
// Multiple filters (all must pass)
244
filter { request -> request.url.protocol.isSecure() }
245
filter { request -> !request.url.pathSegments.contains("health") }
246
}
247
}
248
```
249
250
### Header Sanitization
251
252
Sanitize sensitive headers to prevent their values from appearing in logs.
253
254
```kotlin { .api }
255
/**
256
* Sanitize sensitive headers to avoid their values appearing in the logs
257
* @param placeholder Replacement text for sanitized values (default: "***")
258
* @param predicate Function that returns true if the header should be sanitized
259
*/
260
fun LoggingConfig.sanitizeHeader(placeholder: String = "***", predicate: (String) -> Boolean)
261
```
262
263
**Usage Examples:**
264
265
```kotlin
266
val client = HttpClient {
267
install(Logging) {
268
level = LogLevel.HEADERS
269
270
// Sanitize Authorization header with default placeholder
271
sanitizeHeader { header ->
272
header == "Authorization"
273
}
274
275
// Sanitize multiple headers with custom placeholder
276
sanitizeHeader("█████") { header ->
277
header in listOf("Authorization", "X-API-Key", "Cookie")
278
}
279
280
// Case-insensitive sanitization
281
sanitizeHeader { header ->
282
header.lowercase() == "authorization"
283
}
284
}
285
}
286
```
287
288
## Types
289
290
```kotlin { .api }
291
/**
292
* HTTP request builder used in filter predicates
293
*/
294
class HttpRequestBuilder {
295
val url: URLBuilder
296
val method: HttpMethod
297
val headers: HeadersBuilder
298
val body: Any
299
val attributes: Attributes
300
}
301
302
/**
303
* HTTP method enumeration
304
*/
305
class HttpMethod {
306
companion object {
307
val Get: HttpMethod
308
val Post: HttpMethod
309
val Put: HttpMethod
310
val Delete: HttpMethod
311
val Head: HttpMethod
312
val Options: HttpMethod
313
val Patch: HttpMethod
314
}
315
}
316
317
/**
318
* URL builder for constructing and examining URLs
319
*/
320
class URLBuilder {
321
val protocol: URLProtocol
322
var host: String
323
var port: Int
324
val pathSegments: List<String>
325
val parameters: ParametersBuilder
326
}
327
328
/**
329
* Headers builder for HTTP headers
330
*/
331
class HeadersBuilder {
332
fun append(name: String, value: String)
333
fun contains(name: String): Boolean
334
operator fun get(name: String): String?
335
}
336
337
/**
338
* URL protocol with name and default port
339
*/
340
data class URLProtocol(val name: String, val defaultPort: Int) {
341
companion object {
342
val HTTP: URLProtocol
343
val HTTPS: URLProtocol
344
val WS: URLProtocol
345
val WSS: URLProtocol
346
}
347
}
348
349
/**
350
* Check if the protocol is secure (HTTPS or WSS)
351
*/
352
fun URLProtocol.isSecure(): Boolean
353
354
/**
355
* Parameters builder for URL parameters
356
*/
357
class ParametersBuilder {
358
fun append(name: String, value: String)
359
fun contains(name: String): Boolean
360
operator fun get(name: String): String?
361
}
362
363
/**
364
* Attributes container for request metadata
365
*/
366
class Attributes {
367
fun <T : Any> put(key: AttributeKey<T>, value: T)
368
operator fun <T : Any> get(key: AttributeKey<T>): T
369
fun <T : Any> contains(key: AttributeKey<T>): Boolean
370
}
371
372
/**
373
* Attribute key for type-safe attribute access
374
*/
375
class AttributeKey<T : Any>(val name: String)
376
```
377
378
## Platform-Specific Features
379
380
### JavaScript Environment Integration
381
382
The JavaScript version of the logging plugin provides optimized integration with browser and Node.js environments:
383
384
- **Browser Console**: Logger.DEFAULT and Logger.SIMPLE output to browser console
385
- **Node.js Compatibility**: Works seamlessly with Node.js logging mechanisms
386
- **Async/Await Support**: Full integration with JavaScript async/await patterns
387
- **WebAssembly Support**: Shared implementation works with both JS and WASM targets
388
389
### Error Handling
390
391
The plugin gracefully handles various error conditions:
392
393
- **Malformed Content**: Binary content detection prevents encoding errors
394
- **Network Failures**: Exception logging for failed requests/responses
395
- **Coroutine Safety**: Thread-safe logging operations in concurrent environments
396
- **Content Encoding**: Automatic handling of gzip and other encodings
397
398
### Content Processing
399
400
Advanced content handling capabilities:
401
402
- **Binary Detection**: Automatically detects and handles binary content
403
- **Charset Support**: Proper text encoding/decoding with charset detection
404
- **Streaming Content**: Efficient logging of streaming responses
405
- **Content Length**: Accurate size reporting for various content types
406
407
## Common Usage Patterns
408
409
### Development Setup
410
```kotlin
411
val client = HttpClient {
412
install(Logging) {
413
level = LogLevel.ALL
414
logger = Logger.SIMPLE
415
}
416
}
417
```
418
419
### Production Setup
420
```kotlin
421
val client = HttpClient {
422
install(Logging) {
423
level = LogLevel.INFO
424
logger = Logger.DEFAULT
425
426
// Only log errors and important requests
427
filter { request ->
428
request.url.pathSegments.none { it == "health" }
429
}
430
431
// Sanitize all sensitive headers
432
sanitizeHeader { header ->
433
header.lowercase() in listOf("authorization", "x-api-key", "cookie")
434
}
435
}
436
}
437
```
438
439
### OkHttp-Compatible Logging
440
```kotlin
441
val client = HttpClient {
442
install(Logging) {
443
level = LogLevel.BODY
444
format = LoggingFormat.OkHttp
445
logger = Logger.DEFAULT
446
}
447
}
448
```
449
450
### Testing Setup
451
```kotlin
452
val client = HttpClient {
453
install(Logging) {
454
logger = Logger.EMPTY // No output during tests
455
}
456
}
457
```