在GHCi REPL中打开和关闭hslogger日志文件

时间:2015-03-05 13:24:51

标签: haskell logging io ghci filehandle

在GHCi REPL中运行时,我对hslogger的实现感到恼火。

import System.IO (Handle)
import System.Log.Logger (Priority( DEBUG ), updateGlobalLogger, addHandler, setLevel, debugM)
import System.Log.Handler.Simple (fileHandler)
import System.Log.Handler (setFormatter, close)

main :: IO ()
main = do
    f <- fileHandler "sample.log" DEBUG
    updateGlobalLogger "Component" (addHandler f)
    updateGlobalLogger "Component" (setLevel DEBUG)
    debugM "Component" "This is a sample log line"
    close f

然而,在第一次执行main时,它会毫无例外地运行:

*** Exception: sample.log: hPutStr: illegal operation (handle is closed)

当我在GHCi之外运行程序时,没有这种情况。

我是不是用hslogger正确关闭文件句柄,还是GHCi保持文件句柄打开?

打开和关闭标准文件时,我没有遇到同样的问题。

import System.IO (Handle, openFile, hClose, hPutStrLn, IOMode (WriteMode))

main :: IO ()
main = do
    f <- openFile "sampleFile.log" WriteMode
    hPutStrLn f "Hello"
    hClose f

1 个答案:

答案 0 :(得分:1)

removeHandlerclose结合使用似乎有效:

import System.IO (Handle)
import System.Log.Logger (Priority( DEBUG ), updateGlobalLogger, addHandler, setLevel, debugM, removeHandler)
import System.Log.Handler.Simple (fileHandler)
import System.Log.Handler (setFormatter, close)

main1 :: FilePath -> IO ()
main1 fp = do
    f <- fileHandler fp DEBUG
    updateGlobalLogger "Component" (addHandler f)
    updateGlobalLogger "Component" (setLevel DEBUG)
    debugM "Component" ("This is a sample log line to file " ++ fp)
    updateGlobalLogger "Component" removeHandler
    close f

main = do main1 "foo.log"; main1 "foo.log"