{-# LANGUAGE RecordWildCards #-}
module Logging.Types.Formatter ( Formatter(..) ) where
import Data.Default
import qualified Data.Time.Format as TF
import System.FilePath
import Text.Printf
import Logging.Types.Class.Formattable
import Logging.Types.Record
import Logging.Utils
data Formatter = Formatter { fmt :: String
, datefmt :: String
} deriving (Eq)
instance Default Formatter where
def = Formatter "%(message)s" "%Y-%m-%dT%H:%M:%S%6Q%z"
instance Formattable Formatter where
format f@Formatter{..} rcd@LogRecord{..} = formats fmt
where
diffTime = zonedTimeToPOSIXSeconds created
formats :: String -> String
formats ('%':'%':cs) = ('%' :) $ formats cs
formats ('%':'(':cs) =
case break (== ')') cs of
(attr, ')':c:cs') -> (formatAttr attr c) ++ (formats cs')
_ -> error "Logging.Types.Formattable: no parse (Formatter)"
formats (c:cs) = (c :) $ formats cs
formats "" = ""
formatAttr :: String -> Char -> String
formatAttr "logger" fc = printf ['%', fc] logger
formatAttr "level" fc = printf ['%', fc] $ show level
formatAttr "pathname" fc = printf ['%', fc] $ takeDirectory filename
formatAttr "filename" fc = printf ['%', fc] $ takeFileName filename
formatAttr "module" fc = printf ['%', fc] modulename
formatAttr "lineno" fc = printf ['%', fc] lineno
formatAttr "created" fc = printf ['%', fc] $ timestamp diffTime
formatAttr "asctime" fc = printf ['%', fc] $ formatTime f rcd
formatAttr "msecs" fc = printf ['%', fc] $ microseconds diffTime
formatAttr "message" fc = printf ['%', fc] message
formatAttr _ _ = "unknown"
formatTime Formatter{..} LogRecord{..} =
TF.formatTime TF.defaultTimeLocale datefmt created