Hi - I'm working on my first spray application and wanted to include some 
contextual information in log messages relating to the same incoming 
request and the same overall user journey - coming from Java-land my 
thoughts turned to MDC... Ideally I'd like to use a LoggingAdapter in my 
code and the Slf4jLogger to receive the logging events - but as the Akka 
docs say, you can't safely use the Logging MDC support outside an Actor (in 
fact you can't get at it anyway). To log MDC from a non-Actor, one option 
(described in the Akka docs) is to use logback (say) directly - that is, 
use an Slf4j Logger not a LoggingAdapter and use the Async appender to keep 
things non-blocking - but it feels like it would be nicer to use an Akka 
Logger.

So I had a look at the Logging code 
(https://github.com/akka/akka/blob/master/akka-actor/src/main/scala/akka/event/Logging.scala)
 
to see how the MDC data got sent along to the Logger and it looked to me 
like it would be straightforward to do a variant of the BusLogging 
implementation of the LoggingAdapter trait which grabbed the threadlocal 
MDC and passed it on in the LoggingEvent (using the 2.3.9-style 
LoggingAdapter):

import org.slf4j.MDC
//etc

class MDCLoggingAdapter(val bus: LoggingBus, val logSource: String, val 
logClass: Class[_]) extends LoggingAdapter {

  import akka.event.Logging._
  import scala.collection.JavaConverters._

  def isErrorEnabled = bus.logLevel >= ErrorLevel
  //and so on for other levels

  protected def notifyError(message: String): Unit = 
bus.publish(Error(logSource, logClass, message, retrieveMdc))
  //and so on for other levels

  def retrieveMdc(): Map[String, String] = {
    val contextMap: util.Map[String, String] = MDC.getCopyOfContextMap
    if (contextMap != null) contextMap.asScala.toMap else Map.empty[String, 
String]
  }

}
//plus companion with constructors

Functionally, that appears to work just fine - so my question is: is it 
really just fine? It seems too easy - is there some horrible gotcha that 
will make me sorry later?

Thanks
Stephen Richard

-- 
>>>>>>>>>>      Read the docs: http://akka.io/docs/
>>>>>>>>>>      Check the FAQ: 
>>>>>>>>>> http://doc.akka.io/docs/akka/current/additional/faq.html
>>>>>>>>>>      Search the archives: https://groups.google.com/group/akka-user
--- 
You received this message because you are subscribed to the Google Groups "Akka 
User List" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/akka-user.
For more options, visit https://groups.google.com/d/optout.

Reply via email to