Search code examples
kdb

Get name of function that called current function


I want to be able to get the function name of the function that calls the log function for logging purposes without slowing down or making the log function too complicated.

.log.err:{[x;y]x y}[-2;]

For example, if I call .log.err"log error msg" inside function f1, I want it to append the function name. So it would print "log error msg f1".

I know I could run value .z.s and pass that through to .log.err but I don't want to add an additional argument to the function. Is there any good way to do this?


Solution

  • Credit to Steve Caron for this approach which was posted to the k4 listbox on 2023.05.24:

    f1:{a:1;.log.err"foo";a+x};
    f2:{a:2;.log.err"bar";a+x};
    curstack:{.Q.trp[{'err};();{3_y}]};
    .log.err:{[x;y]x y," - ",last[curstack`][1;3]}[-2;];
    
    q)f1[10]
    foo - f1[10]
    11
    q)f2[10]
    bar - f2[10]
    12
    

    I don't think this will work in every situation - you should study the backtrace output in more detail as you would likely need to generalise this a bit more. https://code.kx.com/q/ref/dotq/#trp-extend-trap