Skip to content

Instantly share code, notes, and snippets.

@xicmiah
Last active February 7, 2018 00:29
Show Gist options
  • Select an option

  • Save xicmiah/cc2b51f79a8f57af5166b41f9fee1fd0 to your computer and use it in GitHub Desktop.

Select an option

Save xicmiah/cc2b51f79a8f57af5166b41f9fee1fd0 to your computer and use it in GitHub Desktop.
Compile-time methods/lines with scala-logging
lazy val root = (project in file("."))
.settings(
inThisBuild(List(
organization := "com.example",
scalaVersion := "2.12.4",
version := "0.1.0-SNAPSHOT"
)),
name := "Hello",
libraryDependencies ++= Seq(
"com.typesafe.scala-logging" %% "scala-logging" % "3.8.0-SNAPSHOT",
"ch.qos.logback" % "logback-classic" % "1.2.3",
"com.lihaoyi" %% "sourcecode" % "0.1.4")
)
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%mdc] %level %logger{36}: %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
package example
import com.typesafe.scalalogging._
import org.slf4j.MDC
import sourcecode._
object Main extends App with PosLogging {
new Foo().doStuff()
logger.info("Hello from main")
}
class Foo extends PosLogging {
def doStuff(): Unit = {
logger.info("Hi from Foo")
}
}
trait PosLogging {
protected val logger: LoggerTakingImplicit[PosLogging.Pos] = Logger.takingImplicit(getClass)(PosLogging.CanLogPos)
}
object PosLogging {
/** Simple wrapper to get both Enclosing and Line */
final case class Pos(enclosing: Enclosing, line: Line) {
def value = s"${enclosing.value}:${line.value}"
}
object Pos {
implicit def generate(implicit enclosing: Enclosing, line: Line): Pos = Pos(enclosing, line)
}
implicit case object CanLogPos extends CanLog[Pos] {
override def logMessage(originalMsg: String, pos: Pos): String = {
MDC.put("pos", pos.value)
originalMsg
}
}
}
[info] Loading project definition from /Users/miah/Code/scratchpad/project
[info] Set current project to Hello (in build file:/Users/miah/Code/scratchpad/)
[info] Running example.Main 
[pos=example.Foo#doStuff:15] INFO example.Foo: Hi from Foo
[pos=example.Main:10] INFO example.Main$: Hello from main
[success] Total time: 1 s, completed Feb 6, 2018 11:44:09 PM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment