Sometimes I perform some calculations, export the results and a week later I notice something odd with one of the exported files. I still keep the notebooks with the calculations but sometimes certain code has been erased and replaced with other code and it's hard to trace what happened.

So I wondered: is there a way to let Mathematica generate some sort of log file that logs the input that it evaluates. I don't want output and I don't want any expansions of input in the log file for otherwise it could become very large and take too much time to generate it.

For example if I wrote and evaluated the following snippets of code

largedata = Import[...];
myFun[ data_, ... ] := ...
foo = myFun[ largeData ]

(Whoops, large output and incorrect as well... Lets redefine myFun, be sloppy with lingering definitions, names, etc...)

myFun[ data_ ] := ...;
foo2 = myFun[ largedata ];
Export[ ..., foo, ... ];

(I feel experimental and write a piece of code that should be faster but it's time for a break and I stop working on it and eventually just leave it there without evaluating)

myFun2[ data_ ] := ....

Then I would like to have a log file (either as part of the notebook or stored in a directory) that reads

[In1] = largedata = Import[...]; 
[In2] = myFun[ data_, ... ] := ...
[In3] = foo = myFun[ largeData ] 
[In4] = myFun[ data_ ] := ...; foo2 = myFun[ largedata ]; Export[ ..., foo, ... ];

1 Answer 1


You may use the variable $Pre that is applied to every input expression before evaluation. Default is not set. If you want to stop logging, you simply say $Pre=. Here is what you do:

ClearAll[log, $Pre]
SetAttributes[log, HoldAll]
log[inp_] := (PutAppend[Unevaluated[inp], "NameOfLogFile"]; inp)
$Pre = log
  • $\begingroup$ Is there a way to define a single function, say StartLogging[ fileName_ ], that applies the procedure above and is available on startup? I tried adding LogInput[ fileName_ ] := ( ClearAll[ LogInputFromNoteBook, $Pre ]; SetAttributes[ log, HoldAll ]; LogInputFromNoteBook[ inp_ ] := ( PutAppend[ Unevaluated[inp], fileName ]; inp); $Pre = LogInputFromNoteBook; ); to the init.m file but evaluating the function does not create a file upon evaluating expressions... $\endgroup$
    – Gert
    Oct 15, 2020 at 9:22
  • $\begingroup$ There are 2 bugs: You must set the attributes of "LogInputFromNoteBook" not of "log"and you must also set the HoldAll attribute of the outer function: "LogInput" $\endgroup$ Oct 15, 2020 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.