or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Ktor Client Logging

1

2

Ktor Client Logging is a plugin for the Ktor HTTP client that provides comprehensive logging capabilities for HTTP requests and responses. It offers configurable log levels, multiple output formats, header sanitization for security, and custom logger implementations with full coroutine safety.

3

4

## Package Information

5

6

- **Package Name**: io.ktor:ktor-client-logging-macosx64

7

- **Package Type**: maven

8

- **Language**: Kotlin (Multiplatform - macOS x64)

9

- **Target Platform**: macOS x64 (Native compilation target)

10

- **Installation**:

11

```kotlin

12

implementation("io.ktor:ktor-client-logging:3.2.0")

13

```

14

15

## Core Imports

16

17

```kotlin

18

import io.ktor.client.plugins.logging.*

19

import io.ktor.client.*

20

import io.ktor.client.request.* // For HttpRequestBuilder (used in filters)

21

import io.ktor.http.* // For HttpMethod, ContentType (used in examples)

22

```

23

24

## Basic Usage

25

26

```kotlin

27

import io.ktor.client.*

28

import io.ktor.client.plugins.logging.*

29

import io.ktor.client.request.*

30

31

// Basic logging setup

32

val client = HttpClient {

33

install(Logging) {

34

level = LogLevel.ALL

35

logger = Logger.SIMPLE

36

}

37

}

38

39

// Make a request - will be automatically logged

40

val response = client.get("https://api.example.com/users")

41

client.close()

42

```

43

44

## Architecture

45

46

The Ktor Client Logging plugin integrates seamlessly with Ktor's client plugin architecture:

47

48

- **Plugin Installation**: Uses Ktor's standard `install()` mechanism with configuration DSL

49

- **Hook System**: Intercepts HTTP pipeline phases (Send, Receive, Response) for comprehensive logging

50

- **Logger Abstraction**: Platform-agnostic Logger interface with concrete implementations

51

- **Coroutine Safety**: Thread-safe logging operations compatible with Ktor's coroutine-based architecture

52

- **Content Handling**: Intelligent binary/text detection and streaming response support

53

54

## Capabilities

55

56

### Plugin Installation and Configuration

57

58

Install and configure the logging plugin in your HTTP client.

59

60

```kotlin { .api }

61

fun HttpClientConfig<*>.Logging(block: LoggingConfig.() -> Unit = {})

62

63

val Logging: ClientPlugin<LoggingConfig>

64

```

65

66

**Usage Example:**

67

68

```kotlin

69

val client = HttpClient {

70

install(Logging) {

71

level = LogLevel.HEADERS

72

logger = Logger.DEFAULT

73

format = LoggingFormat.Default

74

75

// Filter specific requests

76

filter { request ->

77

request.url.host == "api.example.com"

78

}

79

80

// Sanitize sensitive headers

81

sanitizeHeader { header ->

82

header == "Authorization"

83

}

84

}

85

}

86

```

87

88

### Logging Configuration

89

90

Configure logging behavior through the LoggingConfig class.

91

92

```kotlin { .api }

93

@KtorDsl

94

class LoggingConfig {

95

var format: LoggingFormat

96

var logger: Logger

97

var level: LogLevel

98

99

fun filter(predicate: (HttpRequestBuilder) -> Boolean)

100

fun sanitizeHeader(placeholder: String = "***", predicate: (String) -> Boolean)

101

}

102

```

103

104

### Logging Levels

105

106

Control the amount of information logged with different log levels.

107

108

```kotlin { .api }

109

enum class LogLevel(

110

val info: Boolean,

111

val headers: Boolean,

112

val body: Boolean

113

) {

114

ALL(true, true, true),

115

HEADERS(true, true, false),

116

BODY(true, false, true),

117

INFO(true, false, false),

118

NONE(false, false, false)

119

}

120

```

121

122

**Usage Example:**

123

124

```kotlin

125

install(Logging) {

126

level = LogLevel.ALL // Log everything

127

// level = LogLevel.HEADERS // Log info and headers only

128

// level = LogLevel.INFO // Log basic info only

129

// level = LogLevel.NONE // Disable logging

130

}

131

```

132

133

### Logging Formats

134

135

Choose between different output formats for logged information.

136

137

```kotlin { .api }

138

enum class LoggingFormat {

139

Default,

140

OkHttp

141

}

142

```

143

144

**Usage Example:**

145

146

```kotlin

147

install(Logging) {

148

format = LoggingFormat.Default // Standard Ktor format

149

// format = LoggingFormat.OkHttp // OkHttp-compatible format

150

}

151

```

152

153

### Logger Interface

154

155

Implement custom logging behavior through the Logger interface.

156

157

```kotlin { .api }

158

interface Logger {

159

fun log(message: String)

160

161

companion object

162

}

163

```

164

165

### Built-in Loggers

166

167

Platform-specific logger implementations for different environments.

168

169

```kotlin { .api }

170

// Common loggers available on all platforms

171

val Logger.Companion.SIMPLE: Logger

172

val Logger.Companion.EMPTY: Logger

173

174

// Platform-specific default logger

175

expect val Logger.Companion.DEFAULT: Logger

176

```

177

178

**For macOS (Native/POSIX platforms):**

179

```kotlin { .api }

180

actual val Logger.Companion.DEFAULT: Logger // Uses SIMPLE logger

181

```

182

183

**Note:** `Logger.DEFAULT` uses Kotlin Multiplatform's expect/actual mechanism to provide platform-specific implementations. On macOS x64 (and other POSIX platforms), it delegates to `Logger.SIMPLE` which outputs to standard output. This is different from JVM platforms which may use more sophisticated logging frameworks.

184

185

**Usage Examples:**

186

187

```kotlin

188

install(Logging) {

189

logger = Logger.SIMPLE // Prints to stdout with "HttpClient:" prefix

190

// logger = Logger.DEFAULT // Platform-specific logger

191

// logger = Logger.EMPTY // No-op logger for testing

192

193

// Custom logger

194

logger = object : Logger {

195

override fun log(message: String) {

196

println("Custom: $message")

197

}

198

}

199

}

200

```

201

202

### Request Filtering

203

204

Filter which requests should be logged based on custom criteria.

205

206

```kotlin { .api }

207

fun LoggingConfig.filter(predicate: (HttpRequestBuilder) -> Boolean)

208

```

209

210

**Usage Example:**

211

212

```kotlin

213

install(Logging) {

214

// Only log requests to specific domains

215

filter { request ->

216

request.url.host.contains("api.example.com")

217

}

218

219

// Only log POST requests

220

filter { request ->

221

request.method == HttpMethod.Post

222

}

223

224

// Multiple filters (all must pass)

225

filter { request -> request.url.protocol.isSecure() }

226

filter { request -> !request.url.pathSegments.contains("health") }

227

}

228

```

229

230

### Header Sanitization

231

232

Sanitize sensitive header values to prevent exposure in logs.

233

234

```kotlin { .api }

235

fun LoggingConfig.sanitizeHeader(

236

placeholder: String = "***",

237

predicate: (String) -> Boolean

238

)

239

```

240

241

**Note:** When using `LoggingFormat.OkHttp`, the plugin internally uses "██" as the default placeholder regardless of the configured placeholder value.

242

243

**Usage Example:**

244

245

```kotlin

246

install(Logging) {

247

// Sanitize Authorization headers

248

sanitizeHeader { header ->

249

header.equals("Authorization", ignoreCase = true)

250

}

251

252

// Sanitize multiple headers with custom placeholder

253

sanitizeHeader("████") { header ->

254

header in listOf("Authorization", "X-API-Key", "Cookie")

255

}

256

257

// Sanitize based on header patterns

258

sanitizeHeader { header ->

259

header.contains("token", ignoreCase = true) ||

260

header.contains("secret", ignoreCase = true)

261

}

262

}

263

```

264

265

## Error Handling

266

267

The logging plugin is designed to be resilient and will not throw exceptions that interrupt HTTP requests:

268

269

- **Binary Content Detection**: Automatically detects and handles binary content to avoid logging corruption

270

- **Content Length Handling**: Gracefully handles unknown content lengths and streaming responses

271

- **Encoding Support**: Properly handles different character encodings and compressed content

272

- **Exception Isolation**: Logging failures are caught and handled without affecting HTTP operations

273

274

**Common Patterns:**

275

276

```kotlin

277

install(Logging) {

278

level = LogLevel.ALL

279

280

// The plugin will automatically:

281

// - Detect binary vs text content

282

// - Handle streaming responses

283

// - Sanitize specified headers

284

// - Log request/response exceptions

285

// - Preserve original request/response data

286

}

287

```