# Save all input History in a log file

I would like to write some code in my init.m to save all inputs {In[1],In[2],...In[lastone]} right before I close the kernel (or exit Mathematica). Such a script probably should be kernel-specific but I can settle with one log file.

In this way I will be able to review each day's work and assess my productivity. Also I can trace some tweaks I am implementing without the need to remember in which file I did this and that ...

I hope others in SE also would like such an option.

• Can you not do something along the lines of ?? In and then Export["this_session.log",%]? You'd have to not have your $HistoryLength changed. – gpap Nov 20 '13 at 9:59 • If you write the file when you've finished you run the risk of not having anything if there is a kernel crash, power loss etc. – Ymareth Nov 20 '13 at 10:38 • @Ymareth , you are right. So a periodical save would be more suitable right? Using a Dynamic module... – tchronis Nov 20 '13 at 11:10 • Crude answer below and I seem to have misread the question and included Out[n] as well. If not required ignore the setting for$Post. – Ymareth Nov 20 '13 at 13:44

$Epilog := PutAppend[DateList[], DownValues[In], "log.log"]  will do what you want. It assumes the log file exists and will append to it. You could also place the PutAppend in the file end.m, where$Epilog reads from upon exit.

• SCdV thank you. With DownValues[In] i get a list {HoldPattern[In[1]] :>Input1,HoldPattern[In[3]] :>Input3,....} That is a set of rules and this is nice. How can i obtain instead a list : {Hold[Input1],Hold[Input2],....} ? – tchronis Nov 20 '13 at 11:14
• @tchronis DownValues[In] /. RuleDelayed[_, b_] :> Hold[b], or, if you just want to see the text of your input without Hold interfering: DownValues[In] /. RuleDelayed[_, b_] :> HoldForm[b] – Sjoerd C. de Vries Nov 20 '13 at 11:44
• SCdV thank you. Unfortunately the $Epilog value is not working. I have to manually run the command. I inserted it in my init.m file and asking ??$Epilog it outputs correctly Epilog:=({DateList[],DownValues[In]/. (_:>b_):>HoldForm[b]}>>>$UserDocumentsDirectory<>/mathematica.log) but when exiting Mathematica (through the frontend) it is not logging... – tchronis Nov 20 '13 at 14:40 • @tchronis I have tested it using Exit[] to kill the kernel, the log file was indeed created. Did you create the logfile manually first (as mentioned in the answer)? – Sjoerd C. de Vries Nov 20 '13 at 15:40 • @tchronis If you don't mind that the log will be written whenever a window gets closed (including when quiting Mathematica, what we want) then SetOptions[$FrontEnd, FrontEndEventActions -> {"WindowClose" :> (EXITCODE)}] could work for you. – Sjoerd C. de Vries Nov 20 '13 at 21:25

This is a little raw but something along the lines of this should work...

stream = OpenWrite["C:\\Temp\\KitchenSink.math"];
$Pre = (Write[stream, #]; #) &;$Post = (Write[stream, #]; #) &;


When finished...

Clear[$Pre,$Post]