1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Hsm.Log
( Severity(Attention, Info, Trace)
, Log
, makeLoggerIO
, logMsg
, logBlock
, runLog
) where
import Control.Monad (when)
import Data.Function (applyWhen)
import Data.List (intercalate)
import Data.Proxy (Proxy(Proxy))
import Data.Time.Clock (getCurrentTime)
import Data.Time.ISO8601 (formatISO8601Millis)
import Effectful (Dispatch(Static), DispatchOf, Eff, Effect, IOE, (:>))
import Effectful.Dispatch.Static (SideEffects(WithSideEffects), StaticRep, evalStaticRep, getStaticRep, unsafeEff_)
import GHC.Conc.Sync (fromThreadId, myThreadId)
import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)
import String.ANSI (blue, green, red, white)
data Severity
= Attention
| Info
| Trace
deriving (Enum, Eq, Ord)
data Log (d :: Symbol) (a :: * -> *) (b :: *)
type instance DispatchOf (Log d) = Static WithSideEffects
newtype instance StaticRep (Log d) =
Log Severity
makeLoggerIO ::
forall d es. (KnownSymbol d, Log d :> es)
=> Eff es (Severity -> String -> IO ())
makeLoggerIO = getStaticRep >>= \(Log level) -> return $ loggerIO level
where
loggerIO level severity message =
when (severity <= level) $ do
time <- formatISO8601Millis <$> getCurrentTime
threadId <- show . fromThreadId <$> myThreadId
putStrLn $ unwords [time, fmtDomainAndThreadId threadId, fmtSeverity, fmtMessage]
where
fmtDomainAndThreadId threadId = white $ symbolVal (Proxy @d) <> ":" <> threadId
fmtSeverity =
case severity of
Attention -> red "ATTENTION"
Info -> green "INFO"
Trace -> blue "TRACE"
fmtMessage = applyWhen (severity == Attention) red message
logMsg ::
forall d es. (KnownSymbol d, Log d :> es)
=> Severity
-> String
-> Eff es ()
logMsg severity message = makeLoggerIO >>= \loggerIO -> unsafeEff_ $ loggerIO severity message
logBlock ::
forall d es. (KnownSymbol d, Log d :> es)
=> Severity
-> String
-> Eff es ()
logBlock severity message = logMsg severity $ separator <> intercalate separator (lines message)
where
separator = "\n ... "
runLog ::
forall d es a. IOE :> es
=> Severity
-> Eff (Log d : es) a
-> Eff es a
runLog = evalStaticRep . Log
class Logs (ds :: [Symbol]) (es :: [Effect]) where
type Insert ds es :: [Effect]
runLogs :: Severity -> Eff (Insert ds es) a -> Eff es a
instance Logs ('[] :: [Symbol]) (es :: [Effect]) where
type Insert '[] es = es
runLogs _ = id
instance (IOE :> Insert ds es, KnownSymbol d, Logs ds es) => Logs (d : ds :: [Symbol]) (es :: [Effect]) where
type Insert (d : ds) es = Log d : Insert ds es
runLogs level = runLogs @ds level . runLog @d level
|