简体   繁体   中英

Haskell redirect traces to a file

So here i was trying to figure out how to log any anomalies i might get inside my code to a log file. First i noticed the trace function, but then i saw that it only outputs to the stdin .

Then i see the logger module , but that runs inside the IO monad so its a bit of a hassle what with compromising purity and all. Then i figured that if i made a function a->b->b with the a parameter being of type IO () in my case all would be ok.

Indeed the compiler didn't see anything wrong with it but alas the append was never actually called so i was still back to basics. What i actually want to know is : a) Are there any functions that perform IO while still having a pure signature (like unsafePerformIO) that could help me with my logging b) is there any way to force the compiler to evaluate the first parameter in the function i built even though i's never actually used?

thank you guys in advance

Then i figured that if i made a function a->b->b with the a parameter being of type IO () in my case all would be ok.

Nope, wrong. This will do nothing, even if you "evaluate" the first argument. You cannot implement trace without unsafePerformIO .

IO values are just values, no more. Only when they happen in the course of the execution of main (or due to unsafePerformIO ) are they actually executed.

It's not clear, though -- trace outputs to stderr. Is there a reason you can't just do

./MyHaskellExecutable 2>dumpStdErrToThisFile

Logging is side effecting, so has to be in some monad for that effect. Doing otherwise risk the compiler optimizing away your semantically-unnecessary logging calls.

If you are building an app with a plan to support logging, you will need to have it run in some kind of logging environment. IO is overkill, but perhaps a simpler Log monad would be more appropriate (kind of a magic Writer , with ST -like properties of local encapsulation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM