Skip to content

Instantly share code, notes, and snippets.

@sderosiaux
Created June 5, 2017 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sderosiaux/5e19995262c8fbc8d1667e6d350f455c to your computer and use it in GitHub Desktop.
Save sderosiaux/5e19995262c8fbc8d1667e6d350f455c to your computer and use it in GitHub Desktop.
Simple Scala Macro
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