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

Opening and closing a hslogger log file, within the GHCi REPL

当 运行 在 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

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"