Logging in a Matlab Script
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Jan
am 24 Feb. 2011
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 Kommentare
Louis
am 29 Apr. 2020
@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!
Siehe auch
Kategorien
Mehr zu JSON Format finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!