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.
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.