Automatically figuring out function name in f#

  • A+
Category:Languages

If I have a function that is part of a module, and I want a log entry while inside the function,I have to manually print the function namespace and name e.g.

namespace MyModuleNamespace  module MyModule =   let AddTwoNums logger x y =     logger.Info("MyModuleNamespace.AddTwoNums - Start")     let res = x+y     logger.Info("MyModuleNamespace.AddTwoNums - End")     res 

Is there any way I can automatically work out what "MyModuleNamespace.AddTwoNums" is as it is very cumbersome/error prone especially when you have to rename functions and modules during refactoring of code

Even if that cannot be done, is there any way I can automatically work out what "AddTwoNums" is i.e. the function name?

 


There are a couple ways to do this, and I'm not sure which would be the best one for your scenario. One way that I've used in the past is to get the information from the stack trace:

let stackTrace = StackTrace() let topFrame = stackTrace.GetFrame(0) let currentFunction = topFrame.GetMethod() printfn "%s.%s" currentFunction.DeclaringType.Name currentFunction.Name 

In order to keep from having to put these lines in every function, you can make an inline function that does this, which will give you the name of the calling function due to the inlining.

let inline getCurrentFunction () =     let stackTrace = StackTrace()     let topFrame = stackTrace.GetFrame(0)     let currentFunction = topFrame.GetMethod()     sprintf "%s.%s" currentFunction.DeclaringType.Name currentFunction.Name 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: