module Network.Wai.Log (
logRequestsWith
) where
import Data.Aeson ()
import Data.String.Conversions (ConvertibleStrings, StrictText, cs)
import Data.Text (Text)
import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)
import Log
import Network.HTTP.Types.Status
import Network.Wai
logRequestsWith :: (LogT IO () -> IO ()) -> Middleware
logRequestsWith runLogger app req respond = do
runLogger . logInfo "Request received" $ object
[ "method" .= ts (requestMethod req)
, "url" .= ts (rawPathInfo req)
, "remote-host" .= show (remoteHost req)
, "user-agent" .= fmap ts (requestHeaderUserAgent req)
, "body-length" .= show (requestBodyLength req)
]
tStart <- getCurrentTime
app req $ \resp -> do
tEnd <- getCurrentTime
runLogger $ logInfo_ "Sending response"
r <- respond resp
tFull <- getCurrentTime
runLogger . logInfo "Request complete" $ object
[ "status" .= object [ "code" .= statusCode (responseStatus resp)
, "message" .= ts (statusMessage (responseStatus resp))
]
, "time" .= object [ "full" .= diffSeconds tFull tStart
, "process" .= diffSeconds tEnd tStart
]
]
return r
diffSeconds :: UTCTime -> UTCTime -> Double
diffSeconds a b = realToFrac $ diffUTCTime a b
ts :: ConvertibleStrings a StrictText => a -> Text
ts = cs