SLF4J integration for Akka logging system enabling seamless logging with MDC context support.
npx @tessl/cli install tessl/maven-com-typesafe-akka--akka-slf4j-2-10@2.3.00
# Akka SLF4J
1
2
Akka SLF4J provides seamless integration between Akka's actor-based logging system and the Simple Logging Facade for Java (SLF4J) framework. It enables Akka applications to leverage SLF4J's flexible logging architecture while maintaining compatibility with Akka's built-in logging mechanisms.
3
4
## Package Information
5
6
- **Package Name**: akka-slf4j_2.10
7
- **Package Type**: maven
8
- **Language**: Scala
9
- **Installation**: Add to your SBT build:
10
```scala
11
libraryDependencies += "com.typesafe.akka" %% "akka-slf4j" % "2.3.16"
12
```
13
- **Maven Coordinate**: `com.typesafe.akka:akka-slf4j_2.10:2.3.16`
14
15
## Core Imports
16
17
```scala
18
import akka.event.slf4j._
19
```
20
21
For specific components:
22
23
```scala
24
import akka.event.slf4j.{SLF4JLogging, Logger, Slf4jLogger}
25
```
26
27
## Basic Usage
28
29
```scala
30
import akka.actor.{ActorSystem, ActorLogging, Actor, Props}
31
import akka.event.slf4j.{SLF4JLogging, Slf4jLogger}
32
import com.typesafe.config.ConfigFactory
33
34
// Configure Akka to use SLF4J logger
35
val system = ActorSystem("MySystem", ConfigFactory.parseString("""
36
akka {
37
loggers = ["akka.event.slf4j.Slf4jLogger"]
38
loglevel = "INFO"
39
}
40
"""))
41
42
// Use SLF4JLogging trait in your classes
43
class MyService extends SLF4JLogging {
44
def process(data: String): Unit = {
45
log.info("Processing data: {}", data)
46
log.debug("Debug information")
47
}
48
}
49
50
// Use in actors with ActorLogging
51
class MyActor extends Actor with ActorLogging {
52
def receive = {
53
case msg =>
54
log.info("Received message: {}", msg)
55
}
56
}
57
58
val myActor = system.actorOf(Props[MyActor], "myActor")
59
```
60
61
## Architecture
62
63
Akka SLF4J provides three key components for logging integration:
64
65
- **SLF4JLogging Trait**: Provides convenient logging access to any class
66
- **Logger Object**: Factory for creating SLF4J logger instances
67
- **Slf4jLogger Actor**: Core logging actor that handles log events and manages MDC context
68
69
The integration automatically populates SLF4J's Mapped Diagnostic Context (MDC) with valuable debugging information including source thread names, Akka source identifiers, and timestamps.
70
71
## Capabilities
72
73
### SLF4JLogging Trait
74
75
Base trait for classes that want to use the SLF4J logging infrastructure.
76
77
```scala { .api }
78
trait SLF4JLogging {
79
/** Lazy-initialized logger for the class name */
80
@transient
81
lazy val log: org.slf4j.Logger
82
}
83
```
84
85
**Usage Example:**
86
87
```scala
88
import akka.event.slf4j.SLF4JLogging
89
90
class UserService extends SLF4JLogging {
91
def createUser(name: String): User = {
92
log.info("Creating user: {}", name)
93
// ... business logic
94
log.debug("User created successfully")
95
user
96
}
97
}
98
```
99
100
### Logger Factory
101
102
Factory object for obtaining SLF4J logger instances.
103
104
```scala { .api }
105
object Logger {
106
/**
107
* Creates a logger for the given logger name
108
* @param logger Logger name as string
109
* @return SLF4J Logger instance
110
*/
111
def apply(logger: String): org.slf4j.Logger
112
113
/**
114
* Creates a logger for the specified class and source
115
* @param logClass The class to log for
116
* @param logSource The textual representation of the source
117
* @return SLF4J Logger instance
118
*/
119
def apply(logClass: Class[_], logSource: String): org.slf4j.Logger
120
121
/**
122
* Returns the SLF4J Root Logger
123
* @return Root logger instance
124
*/
125
def root: org.slf4j.Logger
126
}
127
```
128
129
**Usage Examples:**
130
131
```scala
132
import akka.event.slf4j.Logger
133
134
// Logger by name
135
val namedLogger = Logger("com.mycompany.MyClass")
136
137
// Logger by class
138
val classLogger = Logger(classOf[MyService], "MyService")
139
140
// Root logger
141
val rootLogger = Logger.root
142
```
143
144
### Slf4jLogger Actor
145
146
Core logging actor that handles Akka log events and manages SLF4J MDC context.
147
148
```scala { .api }
149
class Slf4jLogger extends Actor with SLF4JLogging {
150
/** MDC attribute name for source thread */
151
val mdcThreadAttributeName: String = "sourceThread"
152
153
/** MDC attribute name for Akka source */
154
val mdcAkkaSourceAttributeName: String = "akkaSource"
155
156
/** MDC attribute name for Akka timestamp */
157
val mdcAkkaTimestamp: String = "akkaTimestamp"
158
159
/** Actor receive method handling log events */
160
def receive: Receive
161
162
/**
163
* Sets MDC context for logging operations (inline final method)
164
* @param logSource The source of the log event
165
* @param logEvent The log event containing metadata
166
* @param logStatement The logging statement to execute (call-by-name)
167
*/
168
@inline
169
final def withMdc(logSource: String, logEvent: LogEvent)(logStatement: => Unit): Unit
170
171
/**
172
* Formats timestamp to UTC string (overridable)
173
* @param timestamp Timestamp in milliseconds
174
* @return Formatted UTC timestamp string
175
*/
176
protected def formatTimestamp(timestamp: Long): String
177
}
178
```
179
180
### Log Event Handling
181
182
The Slf4jLogger actor handles these Akka log event types:
183
184
```scala { .api }
185
// Error events with optional exception
186
case class Error(cause: Throwable, logSource: String, logClass: Class[_], message: Any)
187
188
// Warning events
189
case class Warning(logSource: String, logClass: Class[_], message: Any)
190
191
// Info events
192
case class Info(logSource: String, logClass: Class[_], message: Any)
193
194
// Debug events
195
case class Debug(logSource: String, logClass: Class[_], message: Any)
196
197
// Logger initialization (responds with LoggerInitialized)
198
case class InitializeLogger(bus: LoggingBus)
199
200
// Response to logger initialization
201
case object LoggerInitialized
202
```
203
204
## Configuration
205
206
Configure Akka to use the SLF4J logger in your `application.conf`:
207
208
```hocon
209
akka {
210
# Use SLF4J logger
211
loggers = ["akka.event.slf4j.Slf4jLogger"]
212
213
# Set log level
214
loglevel = "INFO"
215
216
# Optional: Set startup timeout
217
logger-startup-timeout = 30s
218
}
219
```
220
221
## MDC Context
222
223
The logger automatically populates SLF4J's Mapped Diagnostic Context with:
224
225
- **sourceThread**: Name of the thread performing the logging
226
- **akkaSource**: Akka source identifier (actor path, etc.)
227
- **akkaTimestamp**: UTC timestamp of the log event
228
- **Custom MDC values**: Any additional context from the log event
229
230
**Example MDC usage with custom values:**
231
232
```scala
233
import akka.actor.{Actor, DiagnosticActorLogging}
234
import akka.event.Logging.MDC
235
236
class OrderProcessor extends Actor with DiagnosticActorLogging {
237
def receive = {
238
case ProcessOrder(orderId, customerId) =>
239
// Set custom MDC values
240
log.mdc(Map(
241
"orderId" -> orderId,
242
"customerId" -> customerId
243
))
244
245
log.info("Processing order")
246
247
// Clear MDC when done
248
log.clearMDC()
249
}
250
}
251
```
252
253
## Error Handling
254
255
The logger handles exceptions in log events by:
256
257
- Logging the exception message and stack trace for errors with causes
258
- Logging just the message for errors without causes (Error.NoCause or null)
259
- Preserving the original exception information in SLF4J format
260
261
**Example error logging:**
262
263
```scala
264
import akka.actor.{Actor, ActorLogging}
265
266
class DataProcessor extends Actor with ActorLogging {
267
def receive = {
268
case ProcessData(data) =>
269
try {
270
// ... process data
271
} catch {
272
case ex: ValidationException =>
273
log.error(ex, "Data validation failed for: {}", data.id)
274
case ex: Exception =>
275
log.error(ex, "Unexpected error processing data")
276
}
277
}
278
}
279
```
280
281
## Types
282
283
```scala { .api }
284
// Re-exported from org.slf4j
285
type Logger = org.slf4j.Logger
286
287
// Akka logging system types (from akka.event)
288
trait LoggingBus
289
290
// Akka logging event types (from akka.event.Logging)
291
sealed trait LogEvent {
292
def logSource: String
293
def logClass: Class[_]
294
def message: Any
295
def timestamp: Long
296
def thread: Thread
297
def mdc: Map[String, Any]
298
}
299
300
case class Error(
301
cause: Throwable,
302
logSource: String,
303
logClass: Class[_],
304
message: Any
305
) extends LogEvent
306
307
case class Warning(
308
logSource: String,
309
logClass: Class[_],
310
message: Any
311
) extends LogEvent
312
313
case class Info(
314
logSource: String,
315
logClass: Class[_],
316
message: Any
317
) extends LogEvent
318
319
case class Debug(
320
logSource: String,
321
logClass: Class[_],
322
message: Any
323
) extends LogEvent
324
```