In a groovy script, I'd like to log important assignments in the code and I'd like to do so, with a simple trait that I can have my classes implement to have to be able to attach the nuanced logging I need to figure out what's happening in the code. Also, it's a way of documenting the code:
trait ExtremeLogger {
Logger logger = Logger.getLogger("...")
def logVar(any) {
logger.debug("${any}")
}
def logLineage(var) {
logger.debug("${var.??getVariableName()??} is assigned to ${logVar(var)}")
}
}
And I understand that at runtime, you may not have direct access to the AST transformations that have happened prior to the evaluation step in JVM.
But I want to know whether there's a series of methods we can call, to obtain the name of the variable without so much cost. Although, if there's cost/overhead in terms of JVM lookups, I'd like to know as well, so I can decide how frequently and what logging level, I'd want to enable such calls.
So I looked up how to get the name of a variable in Groovy and didn't find any conclusive results.
I wonder if the answer is simply just in the real of metaclass? How to get all property names of a Groovy class?
I tried overriding the getAttribute
or getProperty
methods of the metaclass, but no luck so far:
def logLineage(Object var) {
MetaProperty metaProp
var.metaClass.getAttribute = { String name ->
log.info("At least we got here")
metaProp = var.metaClass.getMetaProperty(name)
metaProp.getProperty(delegate)
}
}