3

I have a class with multiple functions

class Foo() {
    fun one() {
        //do something
    }

    fun two() {
        // do something
    }

    fun three() {
        // do something
    }
}

How can I trigger a call to a Logger object that I have, so that in the logs I can see all functions accessed or called, without explicitly placing the log call on every function to keep the code clean. I'm trying to keep a full log trace of all functions called within a service api call, but I don't want to have something like this

class Foo() {
    fun one() {
        log.call()
        //do something
    }

    fun two() {
        log.call()
        // do something
    }

    fun three() {
        log.call()
        // do something
    }
}
avillagomez
  • 443
  • 1
  • 8
  • 18

2 Answers2

2

You can't do it in plain Kotlin.  But this is exactly the sort of thing Aspect-Oriented Programming was intended for.

I haven't used it myself, but if you want to do it in Kotlin, you might look at Spring AOP.  See also discussions here and this question.

gidds
  • 16,558
  • 2
  • 19
  • 26
1

In Java I would write an IvocationHandler to create a dynamic proxy. See this question

Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27