필터 지우기
필터 지우기

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

조회 수: 22 (최근 30일)
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)

채택된 답변

Ameer Hamza
Ameer Hamza 2018년 4월 25일
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
Guillaume
Guillaume 2018년 4월 25일
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 2018년 4월 25일
Thanks to all of you guys, I got it working for me! :)
Is there a big performance drop when I use this?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by