Question about using "diary" command
11 views (last 30 days)
Show older comments
I'm trying to use the "diary()" command to capture the Command Window text to a log file. However, it's not behaving the way I expected. I don't know if I'm doing something wrong, or if I have an incorrect understanding of how "diary()" works.
Below is a toy program demonstrating how I'm using "diary()".
function diary_demo()
[~, host] = system('hostname');
host = host(~isspace(host));
user = getenv('USERNAME');
user = user(~isspace(user));
serial = now();
logfile = sprintf('%s-%s-%f.log', user, host, serial);
diary(logfile);
for i = 1:10
t = datetime('now');
fprintf('now = %s\n', string(t));
pause(1);
end
fprintf('Done!\n');
% With "diary('off')" commented-out, nothing is written to the log file
% until exiting MATLAB.
% With "diary('off')" active, Command Window text is written to the log
% file when the command runs, even if the m-file hasn't finished yet.
fprintf('About to pause 30 seconds before running "diary(''off'')".\n');
pause(30);
diary('off');
fprintf('"diary(''off'')" just ran. About to pause another 30 seconds before exiting the m-file.\n');
pause(30);
fprintf('Exiting m-file.\n');
What I expected was that lines written out to the Command Window (i.e. the datetime info) would be written to my log file at the same time.
What I got was that nothing was written to the log file until the "diary('off')" command ran. (Or until I exited MATLAB.) At that point, everything I had written to the Command Window was written to my log file in one lump.
Am I doing something wrong with the "diary()" command? Or do I have an incorrect understanding of how the "diary()" command works?
0 Comments
Accepted Answer
Matt J
on 7 Jul 2025
Edited: Matt J
on 7 Jul 2025
I don't see anything about it in the documentation, but it makes sense that the file write would be postponed until after all text has been accumulated. Accumulating all of the text first makes it possible for diary() to anticipate the size of the file that is needed, and to allocate space.
More Answers (1)
Steven Lord
on 7 Jul 2025
I'm not 100% sure of this, but perhaps the -logfile startup option would be of use to you. I think it might update the log file more frequently than diary updates the diary file.
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!