Logging in a Matlab Script
조회 수: 13 (최근 30일)
이전 댓글 표시
Hello!
I have an m-script which starts by opening a file handle to a log file. As the script executes, messages are dumped into this textfile so I have a record of the execution and what happened. That works well enough.
Now I have added some functions and objects into by script. I would like to be able to write log messages to this same file while inside the methods of these other code segments.
I do not want to pass and return the file handle on each and every method/function call. The first thing I tried was using a global modifier to allow the filehandle to persist into these other code segments but it seems that even global objects do not exist in the workspace when an object method is called. I would like to avoid printing to the command window (and using DAIRY to save) as I like to keep that "clean" for easy input.
Any ideas? I guess what I'm looking for is either a built-in ability to record data from many locations to one file or a way to have one static object's scope/visibility to be everything.
Thanks!
댓글 수: 0
답변 (1개)
Jan
2011년 2월 24일
You can create a simple function, which acts as file handler:
function WriteLog(Data)
persistent FID
% Open the file
if strcmp(Data, 'open')
FID = fopen(fullfile(tempdir, 'LogFile.txt'), 'w');
if FID < 0
error('Cannot open file');
end
return;
elseif strcmp(Data, 'close')
fclose(FID);
FID = -1;
end
fprintf(FID, '%s\n', Data);
% Write to the screen at the same time:
% fprintf('%s\n', Data);
Now you can open and close the logging from the main function and use in in all other functions.
댓글 수: 4
Louis
2020년 4월 29일
@Jan I think there are two ways: using file handler as you suggested and using diary. Is there a prefered one for general logging? your thoughts on pros and cons of each method will be greatly appreciated. Thank you!
참고 항목
카테고리
Help Center 및 File Exchange에서 JSON Format에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!