3

I want to log all controller methods calls including methodname, methodparams and dont want to write a log to each method. It should handle from one point. is it possible to write interceptor or aspect in swift?

ex. 2016-05-05 09:47:33.927 xxx[58787:27517992] init() method called with params ["xxx", "yyy"]

Thanks.

user2628268
  • 83
  • 1
  • 5

1 Answers1

0

For Swift >=2.2:

You can try to do:

 print("\(NSDate()) \(#file) \(#line) \(#function) in \(self.dynamicType)")

You can use a global method like this:

func VerboseLog<T>(object: T, filename: String = #file, line: Int = #line, funcname: String = #function) {
    print("\(NSDate()) \(filename) \(line) \(funcname) in \(object.dynamicType)")
}

More information:

#file - String - The name of the file in which it appears.

#line - Int - The line number on which it appears.

#column - Int - The column number in which it begins.

#function - String - The name of the declaration in which it appears.

Apple official source.

About aspect oriented programming as you ask, unfortunately Swift dont has now a runtime support. You must refer to obj-c bridging.

There is an interesting library called MOAspect that can be useful if you want to use this kind of approach:

MOAspects.hookClassMethodForClass(UIScreen.self, selector:"mainScreen", position:.Before) {
    NSLog("hooked screen!")
}

UIScreen.mainScreen() // -> hooked screen!
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
  • Its ok for logging, but how can i intercept each method calls and log it there, like @Before pointcut in AOP. – user2628268 May 05 '16 at 08:01
  • Keep in mind that you can also subclassing your controllers with a custom class and add this log in an ovveride method like viewDidLoad – Alessandro Ornano May 05 '16 at 08:14
  • @AlessandroOrnano, this is not what the OP asked for, and it is explicitly mentioned in the second line of the original question. To be more specific, it is only a part of the answer, and not the most important part. – FreeNickname May 05 '16 at 09:24
  • Ok I've update the answer. I hope you find it useful. – Alessandro Ornano May 05 '16 at 09:53
  • I read about swizzling. I will try that firstly. If not able to do then i will try obj-c bridging. – user2628268 May 05 '16 at 11:03