module Network.MoHWS.Logger.Error (
Handle,
start,
stop,
log,
HasHandle(getHandle),
debug,
abort,
debugOnAbort,
logError,
logInfo,
logDebug,
) where
import qualified Network.MoHWS.Logger as Logger
import qualified Network.MoHWS.Logger.Level as LogLevel
import Network.MoHWS.Utility (formatTimeSensibly, )
import System.Time (ClockTime, toUTCTime, getClockTime, )
import Control.Concurrent (myThreadId, )
import Control.Monad.IO.Class (MonadIO, liftIO, )
import Control.Monad.Trans.Class (lift, )
import Control.Monad.Trans.Maybe (MaybeT(MaybeT), runMaybeT, )
import Control.Monad (mzero, )
import Prelude hiding (log, )
data Handle = Handle
{
logger ::Logger.Handle Message,
minLevel :: LogLevel.T
}
data Message = Message
{
time :: ClockTime,
string :: String
}
start :: FilePath -> LogLevel.T -> IO Handle
start file level =
do l <- Logger.start (return . format) file
let h = Handle {
logger = l,
minLevel = level
}
log h LogLevel.Warn $ "Starting error logger with log level "
++ show level ++ "..."
return h
where format m = formatTimeSensibly (toUTCTime (time m))
++ " " ++ string m
stop :: Handle -> IO ()
stop l =
do log l LogLevel.Warn "Stopping error logger..."
Logger.stop (logger l)
log :: Handle -> LogLevel.T -> String -> IO ()
log l level s =
if level < minLevel l
then return ()
else do t <- getClockTime
Logger.log (logger l) (Message t s)
class HasHandle h where
getHandle :: h -> Handle
instance HasHandle Handle where
getHandle = id
debug :: (HasHandle h, MonadIO io) => h -> String -> io ()
debug h s =
liftIO $
do t <- myThreadId
logDebug h $ show t ++ ": " ++ s
abort :: (HasHandle h) => h -> String -> MaybeT IO a
abort h s = lift (debug h s) >> mzero
debugOnAbort :: (HasHandle h) => h -> String -> MaybeT IO a -> MaybeT IO a
debugOnAbort h s act =
MaybeT $
do x <- runMaybeT act
case x of
Nothing -> debug h s
_ -> return ()
return x
logError :: (HasHandle h) => h -> String -> IO ()
logError h = log (getHandle h) LogLevel.Error
logInfo :: (HasHandle h) => h -> String -> IO ()
logInfo h = log (getHandle h) LogLevel.Info
logDebug :: (HasHandle h) => h -> String -> IO ()
logDebug h = log (getHandle h) LogLevel.Debug