packages feed

unkai-0.1.0.1: src/Unkai/Internal/Logger.hs

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

-- |
-- Module      : Unkai.Internal.Logger
-- Copyright   : (c) 2015-2022 Brendan Hay
-- License     : Mozilla Public License, v. 2.0.
-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>
-- Stability   : provisional
-- Portability : non-portable (GHC extensions)
--
-- Types and functions for constructing loggers and emitting log messages.
module Unkai.Internal.Logger
  ( -- * Constructing a Logger
    Logger,
    newLogger,

    -- * Levels
    LogLevel (..),
    logError,
    logDebug,

    -- * Building Messages
    ToLog (..),
  )
where

import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO (..))
import Data.ByteString qualified as BS
import Data.ByteString.Builder (Builder)
import Data.ByteString.Builder qualified as Build
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Types (parseQuery, statusCode)
import System.IO

-- | A callback for informational and diagnostic messages.
type Logger = LogLevel -> Builder -> IO ()

data LogLevel
  = -- | Informational messages supplied by the application.
    Info
  | -- | Error messages.
    Error
  | -- | Request and response summaries.
    Debug
  | -- | The most verbose log threshold. Library diagnostics omit credentials and payloads.
    Trace
  deriving stock (Eq, Ord, Enum, Show)

-- | Write messages at or below the configured threshold to a handle.
newLogger :: (MonadIO m) => LogLevel -> Handle -> m Logger
newLogger threshold handle = liftIO $ do
  hSetBinaryMode handle True
  hSetBuffering handle LineBuffering
  return $ \level message ->
    when (threshold >= level) $
      Build.hPutBuilder handle (message <> "\n")

logError, logDebug :: (MonadIO m, ToLog a) => Logger -> a -> m ()
logError callback = liftIO . callback Error . build
logDebug callback = liftIO . callback Debug . build

class ToLog a where
  build :: a -> Builder

instance ToLog Builder where build = id

instance ToLog BS.ByteString where build = Build.byteString

instance ToLog Int where build = Build.intDec

-- Headers, path captures, query values and payloads can all carry secrets.
-- Keep the summary independent of their contents.
instance ToLog HTTP.Request where
  build req =
    "[Client Request] method="
      <> build (HTTP.method req)
      <> " headers="
      <> build (length (HTTP.requestHeaders req))
      <> " queryParameters="
      <> build (length (parseQuery (HTTP.queryString req)))
      <> " body="
      <> summarizeBody (HTTP.requestBody req)
    where
      summarizeBody = \case
        HTTP.RequestBodyBS bytes -> build (BS.length bytes) <> " bytes"
        HTTP.RequestBodyLBS _ -> "lazy bytes"
        HTTP.RequestBodyBuilder size _ -> Build.int64Dec size <> " bytes"
        HTTP.RequestBodyStream size _ -> Build.int64Dec size <> " streamed bytes"
        HTTP.RequestBodyStreamChunked _ -> "chunked stream"
        HTTP.RequestBodyIO _ -> "deferred"

instance ToLog (HTTP.Response a) where
  build resp =
    "[Client Response] status="
      <> build (statusCode (HTTP.responseStatus resp))
      <> " headers="
      <> build (length (HTTP.responseHeaders resp))