Created
June 5, 2017 08:45
-
-
Save sderosiaux/5e19995262c8fbc8d1667e6d350f455c to your computer and use it in GitHub Desktop.
Simple Scala Macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.reflect.macros.blackbox.Context | |
import scala.language.experimental.macros | |
class LoggerImpl(val c: Context) { | |
import c.universe._ | |
def getClassSymbol(s: Symbol): Symbol = if (s.isClass) s else getClassSymbol(s.owner) | |
def logImpl(msg: Expr[String]): Expr[Unit] = { | |
val cl = getClassSymbol(c.internal.enclosingOwner).toString | |
val time = c.Expr[String](q"new java.util.Date().toString") | |
val logline = c.Expr[String](q""" "[" + $cl + " : " + $time + "]" + $msg """) | |
c.Expr[Unit](q"println($logline)") | |
} | |
} | |
object Logger { | |
def warning(msg: String): Unit = macro LoggerImpl.logImpl | |
} | |
// https://stackoverflow.com/questions/33909930/what-is-the-best-way-to-get-the-name-of-the-caller-class-in-an-object/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment