{-# LANGUAGE OverloadedStrings #-}

module Database.CQL.IO.Tinylog (mkLogger) where

import Data.ByteString.Builder
import Data.ByteString.Lazy (ByteString)
import Database.CQL.IO (Logger (..), LogLevel (..))
import Database.CQL.IO.Hexdump

import qualified Data.ByteString.Lazy as L
import qualified System.Logger        as Tiny

-- | Create a cql-io 'Logger' that delegates log messages to
-- the given tinylog 'Tiny.Logger'. Requests and responses are
-- logged on 'Tiny.Trace' level.
mkLogger :: Tiny.Logger -> Logger
mkLogger l = Logger
    { logMessage  = tinylogMessage  l
    , logRequest  = tinylogRequest  l
    , logResponse = tinylogResponse l
    }

tinylogMessage :: Tiny.Logger -> LogLevel -> Builder -> IO ()
tinylogMessage l lvl msg = Tiny.log l (level lvl) $
    Tiny.msg (toLazyByteString msg)
  where
    level :: LogLevel -> Tiny.Level
    level LogDebug = Tiny.Debug
    level LogInfo  = Tiny.Info
    level LogWarn  = Tiny.Warn
    level LogError = Tiny.Error

tinylogRequest :: Tiny.Logger -> ByteString -> IO ()
tinylogRequest l req = Tiny.log l Tiny.Trace $
    Tiny.msg (hexdump (L.take 160 req))

tinylogResponse :: Tiny.Logger -> ByteString -> IO ()
tinylogResponse l rsp = Tiny.log l Tiny.Trace $
    Tiny.msg (hexdump (L.take 160 rsp))