本文整理汇总了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)
}
}
}
示例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)))
}
}
示例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)
}
}
}
示例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)
}
示例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()
}
}
示例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}"
}
示例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()
}
}
}
示例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])
}
示例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)
}
}
}
示例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)
}
示例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)
}
示例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
}
}
}
示例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)
}
}
}
示例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))
}
}
}
示例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
}
}