How to get the name of the running function/method when executing a class method?

40 views (last 30 days)
Hello everybody,
I have a class with several methods and I want to write my own log-file which tells me if the executed methods threw an error or not. I have a function to save a success-parameter, with a timestamp and the name of the executed method, but how do I get the name of the running method to pass it to the log-function?
I know that I could just type in the name of the method in the function call by hand for every method, but I'm hoping for a better solution.
classdef classname
methods
function test( obj )
write2log( 'test' ); % instead of 'test' there should be a function
% which returns the name of the current function/method
end
end
end
mfilename does not work because it will only give me the name of the m-file, which is the name of the whole class.
Thanks for your help,
Tom
(MATLAB version: Matlab R2016b)

Accepted Answer

Ameer Hamza
Ameer Hamza on 25 Apr 2018
You can use dbstack. It returns function call stack as a struct array. Since you want the name of the lastest function in the call stack, you will need to access the first element of the struct array as shown below
funCallStack = dbstack;
methodName = funCallStack(1).name;
functionName name will have a format like this: '(class_name).(method_name)', you can use strsplit() to seperate the method name
methodNameSeperate = strsplit(methodName, '.');
methodName = methodNameSeperate{end};
  5 Comments
Guillaume
Guillaume on 25 Apr 2018
Personally, I'd just hardcode the function name in the write2log code, rather than use dbstack (which as Stephen pointed out will slow down the execution). But if you were to use dbstack you'd implement it like this:
classdef classname
methods
function test( obj )
write2log();
%....
end
end
end
function write2log
stack = dbstack(1, '-completenames'); %completenames optional. Use 1 to bypass write2log in the call stack
fprintf('%s: %s\n', datetime, stack(1).name);
end
Tom Wenk
Tom Wenk on 25 Apr 2018
Thanks to all of you guys, I got it working for me! :)
Is there a big performance drop when I use this?

Sign in to comment.

More Answers (0)

Categories

Find more on Software Development Tools in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!