Quonux
Quonux

Reputation: 2991

How to redirect trace to file?

The problem I am facing is that I need to somehow redirect the console output of trace to a file, because the result is very large.

I know that its in principle a hidden side effect, but I don't want to use the IO-Monad for that.

I am using Windows.

Upvotes: 0

Views: 281

Answers (1)

jgriego
jgriego

Reputation: 1266

Please, please, please just use IO.


You can, in principle, accomplish this evil deed by using unsafePerformIO :: IO a -> a but it is a terrible, terrible sin and you're liable to run in to wackiness.

It's actually how Debug.Trace does this--here's the source for Debug.Trace.trace:

{-# NOINLINE trace #-}
trace :: String -> a -> a
trace string expr = unsafePerformIO $ do
    traceIO string
    return expr

Note that the NOINLINE pragma is actually important--otherwise GHC might inline your call in multiple places and duplicate the effect that you've hidden from it.


You will certainly have less of a headache after, though, if you just use the IO monad. If you are only writing things, as I imagine, you could also get away with a Writer String and then write the output to the file.

Upvotes: 5

Related Questions