• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala MDC类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.slf4j.MDC的典型用法代码示例。如果您正苦于以下问题:Scala MDC类的具体用法?Scala MDC怎么用?Scala MDC使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MDC类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: CurrentCtxLocalThread

//设置package包名称以及导入依赖的类
package context.propagation.threadlocal

import context.{Ctx, CurrentCtx}
import org.slf4j.MDC

object CurrentCtxLocalThread {
    //val default: CurrentCtx = new CurrentCtxNoop()
    val instance: CurrentCtx = new CurrentCtxLocalThread()
}

class CurrentCtxLocalThread extends CurrentCtx {
    private val currentCtx = new ThreadLocal[Ctx]()
    def get() : Option[Ctx] =  Option(currentCtx.get())
    def set(ctx: Option[Ctx]): Unit = {
        ctx match {
            case Some(c) => {
                currentCtx.set(c)
                MDC.put("currentCtx", c.id)
            }
            case None => {
                currentCtx.remove()
                MDC.remove("currentCtx")
            }
        }
    }
    def withCurrentCtx[T](ctx: Option[Ctx])(f: Option[Ctx] => T): T = {
        val previousCtx = get()
        try {
            set(ctx)
            f(ctx)
        } finally {
            set(previousCtx)
        }
    }
} 
开发者ID:davidB,项目名称:sandbox_context_scala,代码行数:36,代码来源:CurrentCtxThreadLocal.scala


示例2: ErrorHandler

//设置package包名称以及导入依赖的类
package common

import org.slf4j.MDC
import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{Result, RequestHeader}

import scala.concurrent.Future
import scala.util.Try

class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, m: String): Future[Result] = {
    val message = if(m.isEmpty) "there was a problem in the request, please check the path and the headers" else m
    Logger.warn(s"There was a client error with statusCode $statusCode in ${request.method} ${request.path} with message: $message")
    Future.successful(Status(statusCode)(Json.obj("error" -> true, "message" -> message)))
  }

  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val requestId = Try(MDC.get("requestId")).getOrElse{Logger.warn("couldnt get the requestId from MDC");""}
    val message = s"There was a server error in ${request.method} ${request.path} with requestId $requestId"
    Logger.error(message, exception)
    Future.successful(InternalServerError(Json.obj("error" -> true, "message" -> exception.getMessage)))
  }

} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:29,代码来源:ErrorHandler.scala


示例3: LogRequest

//设置package包名称以及导入依赖的类
package controllers

import org.slf4j.MDC
import play.api.Logger
import play.api.mvc.ActionTransformer
import Auth.AuthRequest

import scala.concurrent.Future

object LogRequest extends ActionTransformer[AuthRequest, AuthRequest] {

  private val requestLogger = Logger("requestLogger")

  protected def transform[A](request: AuthRequest[A]) = {
    withMDC(request.user.email)(
      requestLogger.info(s"User Name = ${request.user.fullName}, request = ${request.method} ${request.uri}"))
    Future.successful(request)
  }

  private val UserEmail = "userEmail"

  private def withMDC(userEmail: String)(block: => Unit): Unit = {
    MDC.put(UserEmail, userEmail)
    try {
      block
    } finally {
      MDC.remove(UserEmail)
    }
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:31,代码来源:LogRequest.scala


示例4: MdcExecutionContext

//设置package包名称以及导入依赖的类
package de.geekonaut.slickmdc

import org.slf4j.MDC
import scala.concurrent.ExecutionContext


class MdcExecutionContext(executionContext: ExecutionContext) extends ExecutionContext {
  override def execute(runnable: Runnable): Unit =  {
    val callerMdc = MDC.getCopyOfContextMap
    executionContext.execute(new Runnable {
      def run(): Unit = {
        // copy caller thread diagnostic context to execution thread
        if(callerMdc != null) MDC.setContextMap(callerMdc)
        try {
          runnable.run()
        } finally {
          // the thread might be reused, so we clean up for the next use
          MDC.clear()
        }
      }
    })
  }

  override def reportFailure(cause: Throwable): Unit = executionContext.reportFailure(cause)
} 
开发者ID:AVGP,项目名称:slickmdc,代码行数:26,代码来源:MdcExecutionContext.scala


示例5: logContext

//设置package包名称以及导入依赖的类
package com.pacbio.common.logging

import org.slf4j.MDC
import resource._


trait ContextualLogging {
  def logContext(key: String, value: String): ManagedResource[MDCResource] =
    managed(new MDCResource(key -> value))

  def logContext(pairs: (String, String)*): ManagedResource[MDCResource] =
    managed(new MDCResource(pairs: _*))

  class MDCResource(pairs: (String, String)*) {
    def open(): Unit = pairs.foreach(p => MDC.put(p._1, p._2))
    def close(): Unit = pairs.reverse.foreach(p => MDC.remove(p._1))
  }

  implicit object MDCResource extends Resource[MDCResource] {
    override def open(r: MDCResource) = r.open()
    override def close(r: MDCResource) = r.close()
  }
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:24,代码来源:ContextualLogging.scala


示例6: mdc

//设置package包名称以及导入依赖的类
package one.lockstep.util.internal

trait LoggingModule {
  def mdc[A](entries: (String, Any)*)(thunk: => A): A = {
    import org.slf4j.MDC
    val stash = Option(MDC.getCopyOfContextMap)
    try {
      entries.foreach { case (tag, value) => MDC.put(tag, value.toString) }
      thunk
    } finally {
      stash.fold(ifEmpty = MDC.clear()) { MDC.setContextMap }
    }
  }

  def linenum(implicit file: sourcecode.File, line: sourcecode.Line) =
    "linenum" -> s"${file.value.split("/").last}:${line.value}"
} 
开发者ID:lockstep-one,项目名称:vault,代码行数:18,代码来源:LoggingModule.scala


示例7: LogUtils

//设置package包名称以及导入依赖的类
package com.hypertino.hyperbus.util

import org.slf4j.{Logger, MDC}

object LogUtils {

  implicit class ExtendConfig(val log: Logger) extends AnyVal {
    def trace(mdc: Map[String, Any], s: String) = {
      mdc.foreach(kv ? MDC.put(kv._1, kv._2.toString))
      log.trace(s)
      MDC.clear()
    }

    def debug(mdc: Map[String, Any], s: String) = {
      mdc.foreach(kv ? MDC.put(kv._1, kv._2.toString))
      log.debug(s)
      MDC.clear()
    }

    def info(mdc: Map[String, Any], s: String) = {
      mdc.foreach(kv ? MDC.put(kv._1, kv._2.toString))
      log.info(s)
      MDC.clear()
    }

    def warn(mdc: Map[String, Any], s: String) = {
      mdc.foreach(kv ? MDC.put(kv._1, kv._2.toString))
      log.warn(s)
      MDC.clear()
    }

    def error(mdc: Map[String, Any], s: String, exception: Throwable = null) = {
      mdc.foreach(kv ? MDC.put(kv._1, kv._2.toString))
      if (exception != null)
        log.error(s, exception)
      else
        log.error(s)
      MDC.clear()
    }
  }

} 
开发者ID:hypertino,项目名称:hyperbus,代码行数:43,代码来源:LogUtils.scala


示例8: PersonRepoActor

//设置package包名称以及导入依赖的类
package dal.actors

import akka.actor.{Actor, DiagnosticActorLogging, Props, Status}
import dal.actors.PersonRepoActor.{CreatePerson, GetPersons, PersonCreated, RepoPersons}
import models.Person
import org.slf4j.MDC

class PersonRepoActor extends Actor with DiagnosticActorLogging {

  var currentPersonNr = 0L
  var persons: List[Person] = List.empty[Person]

  val printer = context.actorOf(PrintNewPersonActor.props, "printer")

  def receive = {
    case CreatePerson("mrerror", _) =>
      log.error("mrerror is a bad person, current persons {}", persons)
      sender() ! Status.Failure(new IllegalArgumentException("mrerror is not vaild"))

    case CreatePerson(name, age) =>
      val person = Person(newPersonNr(), name, age)
      MDC.put("pnr", String.valueOf(person.id))
      persons = person +: persons
      log.info("person persisted")
      sender() ! PersonCreated(person)
      printer ! RepoPersons(persons)

    case GetPersons =>
      sender() ! RepoPersons(persons)
  }

  def newPersonNr() = {
    currentPersonNr = currentPersonNr + 1
    currentPersonNr
  }
}

object PersonRepoActor {

  def props = Props(new PersonRepoActor)

  case class CreatePerson(name: String, age: Int)

  case class PersonCreated(person: Person)

  case object GetPersons

  case class RepoPersons(persons: List[Person])
} 
开发者ID:tobnee,项目名称:rp-demo,代码行数:50,代码来源:PersonRepoActor.scala


示例9: loggerName

//设置package包名称以及导入依赖的类
package com.ovoenergy.delivery.service.logging

import com.ovoenergy.comms.model.LoggableEvent
import org.slf4j.{LoggerFactory, MDC}

trait LoggingWithMDC {

  def loggerName: String = getClass.getSimpleName.reverse.dropWhile(_ == '$').reverse

  lazy val log = LoggerFactory.getLogger(loggerName)

  def logDebug(event: LoggableEvent, message: String): Unit = {
    log(event, log.debug(message))
  }

  def logInfo(event: LoggableEvent, message: String): Unit = {
    log(event, log.info(message))
  }

  def logWarn(event: LoggableEvent, message: String): Unit = {
    log(event, log.warn(message))
  }

  def logWarn(event: LoggableEvent, message: String, error: Throwable): Unit = {
    log(event, log.warn(message, error))
  }

  def logError(event: LoggableEvent, message: String, error: Throwable): Unit = {
    log(event, log.error(message, error))
  }

  private def log(event: LoggableEvent, writeToLog: => Unit) {
    event.mdcMap.foreach {
      case (k, v) => MDC.put(k, v)
    }
    try {
      writeToLog
    } finally {
      event.mdcMap.keys.foreach(MDC.remove)
    }
  }

} 
开发者ID:ovotech,项目名称:comms-delivery-service,代码行数:44,代码来源:LoggingWithMDC.scala


示例10: MDCExecutionContext

//设置package包名称以及导入依赖的类
package scala.concurrent

import org.slf4j.MDC


class MDCExecutionContext(mdcContext: java.util.Map[String, String],
                          delegate: ExecutionContext)
    extends ExecutionContextExecutor {
  def execute(runnable: Runnable) =
    delegate.execute(new Runnable {
      def run() {
        val oldMDCContext = MDC.getCopyOfContextMap
        setContextMap(mdcContext)
        try {
          runnable.run()
        } finally {
          setContextMap(oldMDCContext)
        }
      }
    })

  private[this] def setContextMap(context: java.util.Map[String, String]) {
    if (context == null) {
      MDC.clear()
    } else {
      MDC.setContextMap(context)
    }
  }

  def reportFailure(t: Throwable) = delegate.reportFailure(t)
} 
开发者ID:mdedetrich,项目名称:mdc-async,代码行数:32,代码来源:MDCExecutionContext.scala


示例11: TraceableExecutionContext

//设置package包名称以及导入依赖的类
package cores.traceable.internal

import java.util.Map

import org.slf4j.MDC

import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
import scala.util.control.Exception.{Catch, ultimately}


private[internal] final class TraceableExecutionContext(mdcContext: Map[String, String], delegate: ExecutionContext) extends ExecutionContextExecutor {
  def execute(runnable: Runnable): Unit = delegate.execute(new Runnable {
    def run() {
      val oldMDCContext = MDC.getCopyOfContextMap
      setContextMap(mdcContext)
      withResetContext(oldMDCContext) {
        runnable.run()
      }
    }
  })

  private[this] def setContextMap(context: Map[String, String]) {
    Option(context) match {
      case Some(c) => MDC.setContextMap(c)
      case None => MDC.clear()
    }
  }

  private def withResetContext(context: Map[String, String]): Catch[Unit] = {
    ultimately[Unit] {
      setContextMap(context)
    }
  }

  def reportFailure(t: Throwable): Unit = delegate.reportFailure(t)
} 
开发者ID:tmknom,项目名称:scala-ddd,代码行数:37,代码来源:TraceableExecutionContext.scala


示例12: MDCFilter

//设置package包名称以及导入依赖的类
package cores.filter

import javax.inject.{Inject, Singleton}

import akka.stream.Materializer
import cores.internal.constant.MdcKey
import cores.internal.request.RequestIdStore
import org.slf4j.MDC
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}


@Singleton
@SuppressWarnings(Array("org.wartremover.warts.ImplicitParameter"))
final class MDCFilter @Inject()(implicit override val mat: Materializer,
                                exec: ExecutionContext) extends Filter {
  def apply(nextFilter: RequestHeader => Future[Result])
           (requestHeader: RequestHeader): Future[Result] = {

    MDC.put(MdcKey.RequestId, RequestIdStore.extract(requestHeader).value)

    nextFilter(requestHeader).map { result =>
      // MDC????????????????????????
      // ?????????????????????????????
      MDC.remove(MdcKey.RequestId)
      result
    }
  }
} 
开发者ID:tmknom,项目名称:scala-ddd,代码行数:31,代码来源:MDCFilter.scala


示例13: ExecutionStart

//设置package包名称以及导入依赖的类
package cores.task.internal

import cores.internal.constant.MdcKey
import cores.internal.request.RequestId
import org.slf4j.MDC
import play.api.{Application, Logger, Play}

import scala.util.control.Exception.{Catch, ultimately}
import scala.util.{Failure, Success, Try}


private[task] object ExecutionStart {
  private val startTime: Long = System.currentTimeMillis()

  def start(execution: Execution): Unit = {
    val app: Application = startApplication()
    withCleanup(app) {
      executeQuietly(execution, app)
    }
  }

  private def executeQuietly(execution: Execution, app: Application): Unit = {
    Try(execution.execute(app)) match {
      case Success(_) => Logger.info(s"${execution.getClass.getSimpleName} is success.")
      case Failure(e) => Logger.error(s"${execution.getClass.getSimpleName} is error!", e)
    }
  }

  private def startApplication(): Application = {
    MDC.put(MdcKey.RequestId, RequestId.initialize().value)
    Logger.info("Starting application.")
    ApplicationInitializer.initialize()
  }

  private def withCleanup(app: Application): Catch[Unit] = {
    ultimately[Unit] {
      Play.stop(app)
      val endTime: Float = (System.currentTimeMillis() - startTime) / 1000f
      Logger.info(s"Stopping application, total time: ${"%.1f".format(endTime)} s.")
      MDC.remove(MdcKey.RequestId)
    }
  }
} 
开发者ID:tmknom,项目名称:scala-ddd,代码行数:44,代码来源:ExecutionStart.scala


示例14: TraceableActionSpec

//设置package包名称以及导入依赖的类
package cores.traceable

import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.slf4j.MDC
import play.api.mvc.{Action, AnyContent, Controller}
import play.api.test.FakeRequest
import play.api.test.Helpers._

class TraceableActionSpec extends PlaySpec with BeforeAndAfterEach {
  private val MdcKey = "sampleKey"

  override def afterEach(): Unit = {
    MDC.remove(MdcKey)
  }

  "TraceableAction" should {
    "MDC???????????" in {
      MDC.put(MdcKey, "value")
      val actual = contentAsString((new TraceableController).index().apply(FakeRequest()))
      actual mustBe "value"
    }
  }

  private class TraceableController extends Controller {
    def index: Action[AnyContent] = TraceableAction {
      Ok(MDC.get(MdcKey))
    }
  }
} 
开发者ID:tmknom,项目名称:scala-ddd,代码行数:31,代码来源:TraceableActionSpec.scala


示例15: myExceptionHandler

//设置package包名称以及导入依赖的类
package allawala.chassis.http.route

import java.util.UUID

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server._
import allawala.chassis.auth.exception.AuthenticationException
import allawala.chassis.core.exception.{DomainException, UnexpectedException}
import org.apache.shiro.authc.{AuthenticationException => ShiroAuthenticationException}
import org.slf4j.MDC

trait RouteWrapper extends RouteSupport {

  def myExceptionHandler: ExceptionHandler = {
    import io.circe.generic.auto._

    ExceptionHandler {
      // This can happen on a Future.failed { with some domain exception}
      case e: DomainException =>
        extractRequest { request =>
          logError(request, e)
          complete(e.statusCode -> e.toErrorEnvelope(MDC.get(XCorrelationId)))
        }
      case e: IllegalArgumentException =>
        extractRequest { request =>
          val ue = UnexpectedException(errorCode = "invalid.request", e)
          logError(request, ue)
          complete(BadRequest -> ue.toErrorEnvelope(MDC.get(XCorrelationId)))
        }
      case e: ShiroAuthenticationException =>
        extractRequest { request =>
          val ae = AuthenticationException(message = e.getMessage, cause = e)
          logError(request, ae)
          complete(ae.statusCode -> ae.toErrorEnvelope(MDC.get(XCorrelationId)))
        }
      case e: NoSuchElementException =>
        // For akka http cors. Ignore logging
        complete(NotFound -> e.getMessage)
      case e: Exception =>
        extractRequest { request =>
          val ue = UnexpectedException(cause = e)
          logError(request, ue)
          complete(InternalServerError -> ue.toErrorEnvelope(MDC.get(XCorrelationId)))
        }
    }
  }

  val correlationHeader: Directive1[String] =
    optionalHeaderValueByName(XCorrelationId) map { optId =>
      val id = optId.getOrElse(UUID.randomUUID().toString)
      MDC.put(XCorrelationId, id)
      id
    }

} 
开发者ID:allawala,项目名称:service-chassis,代码行数:56,代码来源:RouteWrapper.scala


示例16: loggableEventToString

//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.composer

import com.ovoenergy.comms.model.LoggableEvent
import org.slf4j.{Logger, LoggerFactory, MDC}

trait Logging {

  val log: Logger = LoggerFactory.getLogger(getClass)

  private def loggableEventToString(event: LoggableEvent): String = {
    event.loggableString.map(ls => s": \n$ls").getOrElse("")
  }

  def debug[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.debug(message))
  }

  def info[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.info(message))
  }

  def infoE[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.info(s"$message${loggableEventToString(a)}"))
  }

  def warn[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.warn(message))
  }

  def warnT[A <: LoggableEvent](a: A)(message: String, throwable: Throwable): Unit = {
    withMDC(a)(log.warn(message, throwable))
  }

  private def withMDC[A <: LoggableEvent](a: A)(block: => Unit): Unit = {
    a.mdcMap.foreach { case (mdcParam, mdcValue) => MDC.put(mdcParam, mdcValue) }
    try {
      block
    } finally {
      a.mdcMap.foreach { case (mdcParam, _) => MDC.remove(mdcParam) }
    }
  }
} 
开发者ID:ovotech,项目名称:comms-composer,代码行数:43,代码来源:Logging.scala


示例17: loggableEventToString

//设置package包名称以及导入依赖的类
package postman.infrastructure

import com.ovoenergy.comms.model.LoggableEvent
import org.slf4j.{Logger, LoggerFactory, MDC}

trait Logging {

  val log: Logger = LoggerFactory.getLogger(getClass)

  private def loggableEventToString(event: LoggableEvent): String = {
    event.loggableString.map(ls => s": \n$ls").getOrElse("")
  }

  def debug[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.debug(message))
  }

  def info[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.info(message))
  }

  def infoE[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.info(s"$message${loggableEventToString(a)}"))
  }

  def warn[A <: LoggableEvent](a: A)(message: String): Unit = {
    withMDC(a)(log.warn(message))
  }

  def warnT[A <: LoggableEvent](a: A)(message: String, throwable: Throwable): Unit = {
    withMDC(a)(log.warn(message, throwable))
  }

  private def withMDC[A <: LoggableEvent](a: A)(block: => Unit): Unit = {
    a.mdcMap.foreach { case (mdcParam, mdcValue) => MDC.put(mdcParam, mdcValue) }
    try {
      block
    } finally {
      a.mdcMap.foreach { case (mdcParam, _) => MDC.remove(mdcParam) }
    }
  }
} 
开发者ID:ovotech,项目名称:comms-postman,代码行数:43,代码来源:Logging.scala


示例18: LoggingWithMDC

//设置package包名称以及导入依赖的类
package com.ovoenergy.event.gateway.manager.logging

import com.ovoenergy.event.gateway.manager.logging.LoggingWithMDC.MDCParameter
import org.slf4j.{LoggerFactory, MDC}

object LoggingWithMDC {
  sealed trait MDCParameter { val key: String }
  case object TraceTokenMDC extends MDCParameter { val key = "traceToken" }
  case object ChannelMDC    extends MDCParameter { val key = "channel"    }
  case object GatewayMDC    extends MDCParameter { val key = "gateway"    }
}

trait LoggingWithMDC {
  def loggerName: String

  lazy private val log = LoggerFactory.getLogger(loggerName)

  def logDebug(mdcParams: Map[MDCParameter, String], message: String): Unit = {
    log(mdcParams, () => log.debug(message))
  }

  def logDebug(mdcParams: Map[MDCParameter, String], message: String, error: Throwable): Unit = {
    log(mdcParams, () => log.debug(message, error))
  }

  def logInfo(mdcParams: Map[MDCParameter, String], message: String): Unit = {
    log(mdcParams, () => log.info(message))
  }

  def logInfo(mdcParams: Map[MDCParameter, String], message: String, error: Throwable): Unit = {
    log(mdcParams, () => log.info(message, error))
  }

  def logWarn(mdcParams: Map[MDCParameter, String], message: String): Unit = {
    log(mdcParams, () => log.warn(message))
  }

  def logError(mdcParams: Map[MDCParameter, String], message: String): Unit = {
    log(mdcParams, () => log.error(message))
  }

  def logError(mdcParams: Map[MDCParameter, String], message: String, error: Throwable): Unit = {
    log(mdcParams, () => log.error(message, error))
  }

  def logWarn(mdcParams: Map[MDCParameter, String], message: String, error: Throwable): Unit = {
    log(mdcParams, () => log.warn(message, error))
  }

  private def log(mdcParams: Map[MDCParameter, String], loggingFunction: () => Unit) {
    try {
      mdcParams.foreach { case (param, value) => MDC.put(param.key, value) }
      loggingFunction()
    } finally {
      mdcParams.foreach { case (param, _) => MDC.remove(param.key) }
    }

  }

} 
开发者ID:ovotech,项目名称:comms-gateway-event-manager,代码行数:61,代码来源:LoggingWithMDC.scala


示例19: MdcExecutionContext

//设置package包名称以及导入依赖的类
package logging

import scala.concurrent.{Future, ExecutionContextExecutor, ExecutionContext}
import org.slf4j.MDC
import play.api.mvc.{Result, Request, ActionBuilder}


object MdcExecutionContext {
  object Implicit {
    implicit def defaultContext: ExecutionContext = fromThread
  }

  def fromThread: ExecutionContext = new MdcExecutionContext(MDC.getCopyOfContextMap, play.api.libs.concurrent.Execution.defaultContext)
}

class MdcExecutionContext(context: java.util.Map[String, String], parent: ExecutionContext) extends ExecutionContextExecutor {
  def execute(runnable: Runnable) = parent.execute(new Runnable {
    def run() {
      val previous = MDC.getCopyOfContextMap
      if (context == null) {
        MDC.clear()
      } else {
        MDC.setContextMap(context)
      }
      try {
        runnable.run()
      } finally {
        if (previous != null)
          MDC.setContextMap(previous)
      }
    }
  })

  def reportFailure(t: Throwable) = parent.reportFailure(t)
}

object MdcAction extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = block(request)
  override def executionContext: ExecutionContext = MdcExecutionContext.fromThread
} 
开发者ID:UKHomeOffice,项目名称:submission-service,代码行数:41,代码来源:MdcExecutionContext.scala


示例20: aroundReceive

//设置package包名称以及导入依赖的类
package submission

import akka.actor.Actor
import model.Message
import org.slf4j.{LoggerFactory, MDC}

trait MdcLoggingActor extends Actor {

  protected val logger = LoggerFactory.getLogger(this.getClass)

  override def aroundReceive(receive: Receive, msg: Any): Unit = {

    try {
      msg match {
        case m:Message =>
          MDC.put("application_id", m.applicationId.getOrElse("Unknown"))
          MDC.put("message_id", m.id.fold("Unknown")(_.stringify))
        case _ =>
          MDC.put("application_id", "NONE")
          MDC.put("message_id", "NONE")
      }
      super.aroundReceive(receive, msg)
    } finally {
      MDC.clear()
    }
  }

} 
开发者ID:UKHomeOffice,项目名称:submission-service,代码行数:29,代码来源:MdcLoggingActor.scala



注:本文中的org.slf4j.MDC类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala BuiltInComponentsFromContext类代码示例发布时间:2022-05-23
下一篇:
Scala Element类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap