{-# LANGUAGE OverloadedStrings #-}
module Database.CQL.IO.Log
( Logger (..)
, LogLevel (..)
, nullLogger
, stdoutLogger
, logDebug
, logInfo
, logWarn
, logError
, module BB
) where
import Control.Monad (when)
import Data.ByteString.Builder as BB
import Data.ByteString.Lazy (ByteString)
import Database.CQL.IO.Hexdump
import Data.Semigroup ((<>))
import qualified Data.ByteString.Lazy.Char8 as Char8
data Logger = Logger
{ logMessage :: LogLevel -> Builder -> IO ()
, logRequest :: ByteString -> IO ()
, logResponse :: ByteString -> IO ()
}
data LogLevel
= LogDebug
| LogInfo
| LogWarn
| LogError
deriving (Eq, Ord, Show, Read)
nullLogger :: Logger
nullLogger = Logger
{ logMessage = \_ _ -> return ()
, logRequest = \_ -> return ()
, logResponse = \_ -> return ()
}
stdoutLogger :: LogLevel -> Logger
stdoutLogger l = Logger
{ logMessage = \l' m -> when (l <= l') $
Char8.putStrLn (withLevel l' (toLazyByteString m))
, logRequest = \rq -> when (l <= LogDebug) $
Char8.putStrLn (hexdump rq)
, logResponse = \rs -> when (l <= LogDebug) $
Char8.putStrLn (hexdump rs)
}
where
withLevel LogDebug m = "[Debug] " <> m
withLevel LogInfo m = "[Info] " <> m
withLevel LogWarn m = "[Warn] " <> m
withLevel LogError m = "[Error] " <> m
logDebug :: Logger -> Builder -> IO ()
logDebug l = logMessage l LogDebug
{-# INLINE logDebug #-}
logInfo :: Logger -> Builder -> IO ()
logInfo l = logMessage l LogInfo
{-# INLINE logInfo #-}
logWarn :: Logger -> Builder -> IO ()
logWarn l = logMessage l LogWarn
{-# INLINE logWarn #-}
logError :: Logger -> Builder -> IO ()
logError l = logMessage l LogError
{-# INLINE logError #-}