当前位置: 首页>>代码示例>>Scala>>正文


Scala MDC类代码示例

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


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


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