Skip to content

A peer-to-peer stack for code collaboration

Extract logging into separate module

Thomas Scholtes707002fc0708
diff --git a/exe/Daemon.hs b/exe/Daemon.hs
index 1f529c0..c83b1cd 100644
--- a/exe/Daemon.hs
+++ b/exe/Daemon.hs
@@ -17,10 +17,10 @@ import Options.Applicative
import Servant
import System.IO (BufferMode(..), hSetBuffering)
-import Radicle.Daemon.Common hiding (logInfo)
-import qualified Radicle.Daemon.Common as Common
+import Radicle.Daemon.Common
import qualified Radicle.Daemon.HttpApi as Api
import Radicle.Daemon.Ipfs
+import Radicle.Daemon.Logging
import Radicle.Daemon.MachineConfig
import Radicle.Daemon.Monad
@@ -34,7 +34,7 @@ import qualified Radicle.Internal.UUID as UUID
-- * Types
logDaemonError :: MonadIO m => Error -> m ()
-logDaemonError (displayError -> (m, xs)) = logErr m xs
+logDaemonError (displayError -> (m, xs)) = logError' m xs
-- * Main
@@ -87,7 +87,7 @@ main = do
Opts{..} <- execParser =<< cliInfo
machineConfigFileLock <- newMVar ()
machines <- CachedMachines <$> CMap.empty
- let env = Env{ logLevel = if debug then Debug else Normal, ..}
+ let env = Env{ logLevel = if debug then LogDebug else LogInfo, ..}
machineConfig <- readMachineConfigIO machineConfigFileLock machineConfigFile
initRes <- runDaemon env (init machineConfig)
case initRes of
@@ -97,19 +97,19 @@ main = do
Right _ -> do
polling <- async $ initPolling env
let app = serve Api.daemonApi (server env)
- Common.logInfo "Start listening" [("port", show port)]
+ runDaemon env $ logInfo "Start listening" [("port", show port)]
serv <- async $ run port app
exc <- waitEitherCatchCancel polling serv
case exc of
Left (Left err) -> do
- logErr "Polling failed with an exception" [("error", toS (displayException err))]
+ logError' "Polling failed with an exception" [("error", toS (displayException err))]
exitFailure
Left (Right void') -> absurd void'
Right (Left err) -> do
- logErr "Server failed with an exception" [("error", toS (displayException err))]
+ logError' "Server failed with an exception" [("error", toS (displayException err))]
exitFailure
Right (Right ()) -> do
- logErr "Server stopped (this should not happen)" []
+ logError' "Server stopped (this should not happen)" []
exitFailure
server :: Env -> Server Api.DaemonApi
@@ -155,7 +155,7 @@ newMachine :: Daemon Api.NewResponse
newMachine = do
id <- ipfs createMachine CouldNotCreateMachine
sub <- initDaemonSubscription id
- logInfo Normal "Created new IPFS machine" [("machine-id", getMachineId id)]
+ logInfo "Created new IPFS machine" [("machine-id", getMachineId id)]
m <- liftIO $ emptyMachine id Writer sub
insertNewMachine id (Cached m)
actAsWriter m
@@ -175,7 +175,7 @@ query id (Api.QueryRequest v) = do
case fst <$> runIdentity $ runLang (machineState m) $ eval v of
Left err -> throwError $ MachineError id (InvalidInput err)
Right rv -> do
- logInfo Normal "Handled query" [("machine-id", getMachineId id)]
+ logInfo "Handled query" [("machine-id", getMachineId id)]
pure (Api.QueryResponse rv)
-- | Write a new expression to an IPFS machine.
@@ -199,7 +199,7 @@ send id (Api.SendRequest expressions) = do
requestInput (machineSubscription m)
Just (Cached Machine{ machineMode = Reader, ..}) -> requestInput machineSubscription
Just (Cached Machine{ machineMode = Writer }) -> do
- logInfo Normal "Applying input"
+ logInfo "Applying input"
[ ("machine-id", getMachineId id)
]
results <- writeInputs id expressions Nothing
@@ -212,14 +212,14 @@ send id (Api.SendRequest expressions) = do
nonce <- liftIO $ UUID.uuid
asyncMsg <- liftIO $ async $ subscribeOne sub ackWaitTime (matchMessage nonce)
machineIpfs id $ publish id (Submit SubmitInputs{..})
- logInfo Debug
+ logInfo
"Sent input request to writer"
[ ("machine-id", getMachineId id)
, ("expressions", prValues expressions) ]
msg_ <- machineIpfs id $ wait asyncMsg
case msg_ of
Just results -> do
- logInfo Normal
+ logInfo
"Writer accepted input request"
[ ("machine-id", getMachineId id)
, ("results", prValues results)
@@ -233,14 +233,6 @@ send id (Api.SendRequest expressions) = do
-- * Helpers
-logInfo :: LogLevel -> Text -> [(Text,Text)] -> Daemon ()
-logInfo l msg infos = do
- l' <- asks logLevel
- if l <= l'
- then Common.logInfo msg infos
- else pure ()
-
-
lookupMachine :: MachineId -> Daemon (Maybe CachedMachine)
lookupMachine id = do
msCMap <- asks machines
@@ -280,7 +272,7 @@ initDaemonSubscription id =
machineIpfs id $ initSubscription id logNonDecodableMsg
where
logNonDecodableMsg bad =
- Common.logInfo "Non-decodable message on machine's pubsub topic"
+ logError' "Non-decodable message on machine's pubsub topic"
[("machine-id", getMachineId id), ("message", bad)]
-- | Turns a 'Daemon' subscription handler into an IO one. Errors which are
@@ -342,7 +334,7 @@ machineIpfs id io = ipfs io (MachineError id . IpfsError)
bumpPolling :: MachineId -> Daemon ()
bumpPolling id = do
modifyMachine id $ \m -> pure (m { machinePolling = highFreq }, () )
- logInfo Debug "Reset to high-frequency polling" [("machine-id", getMachineId id)]
+ logDebug "Reset to high-frequency polling" [("machine-id", getMachineId id)]
-- | Insert a new machine into the cache.
insertNewMachine :: MachineId -> CachedMachine -> Daemon ()
@@ -394,8 +386,8 @@ initAsReader id = do
m <- loadMachine Reader id
env <- ask
_ <- liftIO $ addHandler (machineSubscription m) (daemonHandler env onMsg)
- logInfo Normal "Following as reader" [ ("machine-id", getMachineId id)
- , ("current-input-index", show (machineLastIndex m)) ]
+ logInfo "Following as reader" [ ("machine-id", getMachineId id)
+ , ("current-input-index", show (machineLastIndex m)) ]
pure m
where
onMsg :: Message -> Daemon ()
@@ -421,7 +413,7 @@ newReader id = do
initReaderNoFail :: MachineId -> Daemon ()
initReaderNoFail id = catchError (initAsReader id $> ()) $ \err -> do
let (msg, infos) = displayError err
- logErr "Could not initiate reader-mode machine on startup" $ ("init-error", msg) : infos
+ logError' "Could not initiate reader-mode machine on startup" $ ("init-error", msg) : infos
t <- liftIO Time.getSystemTime
insertNewMachine id (UninitialisedReader t)
@@ -435,13 +427,13 @@ refreshAsReader id = modifyMachine id refresh
(newIdx, is) <- machineIpfs id $ machineInputsFrom (machineId m) (Just currentIdx)
if currentIdx == newIdx
then do
- logInfo Debug
+ logDebug
"Reader is already up to date"
[mid, ("input-index", show newIdx)]
pure (m, m)
else do
(m', _) <- addInputs is (pure newIdx) (const (pure ())) m
- logInfo Debug
+ logDebug
"Updated reader"
[mid, ("n", show (length is)), ("input-index", show newIdx)]
pure (m', m')
@@ -462,7 +454,7 @@ actAsWriter :: Machine -> Daemon ()
actAsWriter m = do
env <- ask
_ <- liftIO $ addHandler (machineSubscription m) (daemonHandler env onMsg)
- logInfo Normal "Acting as writer" [("machine-id", getMachineId id)]
+ logInfo "Acting as writer" [("machine-id", getMachineId id)]
where
id = machineId m
onMsg = \case
@@ -479,8 +471,10 @@ writeInputs :: MachineId -> [Value] -> Maybe Text -> Daemon [Value]
writeInputs id is nonce = do
(rs, idx) <- modifyMachine id (addInputs is write pub)
writeMachineConfig
- logInfo Debug "Wrote inputs to IPFS" [ ("machine-id", getMachineId id)
- , ("new-input-index", show idx) ]
+ logDebug "Wrote inputs to IPFS"
+ [ ("machine-id", getMachineId id)
+ , ("new-input-index", show idx)
+ ]
pure rs
where
write = machineIpfs id $ writeIpfs id is
@@ -510,7 +504,7 @@ poll = do
-- Low frequency polling is every 10 seconds.
LowFreq -> (delta > lowFreqPollPeriod, LowFreq)
when shouldPoll $ do
- logInfo Debug "Polling.." [("machine-id", getMachineId machineId)]
+ logDebug "Polling.." [("machine-id", getMachineId machineId)]
refreshAsReader machineId >> pure ()
modifyMachine machineId $ \m' -> pure (m' { machinePolling = newPoll }, ())
UninitialisedReader t -> do
diff --git a/src/Radicle/Daemon/Common.hs b/src/Radicle/Daemon/Common.hs
index 8de15a8..40380fa 100644
--- a/src/Radicle/Daemon/Common.hs
+++ b/src/Radicle/Daemon/Common.hs
@@ -4,15 +4,12 @@ module Radicle.Daemon.Common
, Machine(..)
, CachedMachine(..)
, CachedMachines(..)
- , logInfo
- , logErr
, advanceChain
) where
import Protolude hiding (log)
import qualified Data.Aeson as A
-import qualified Data.Text as T
import qualified Data.Time.Clock.System as Time
import Radicle
@@ -55,25 +52,6 @@ data CachedMachine
newtype CachedMachines = CachedMachines { getMachines :: CMap.CMap MachineId CachedMachine }
--- | Log a message to @stdout@.
---
--- The second argument is a list of key-value pairs that will be joined with "="
--- and appended to the message.
---
--- @
--- log "INFO" "the message" [("foo", "5)]
--- -- prints "INFO the message foo=5"
--- @
-log :: MonadIO m => Text -> Text -> [(Text, Text)] -> m ()
-log typ msg dat = do
- putStrLn $ typ <> " " <> msg <> datString
- where
- datString = T.intercalate "" $ map (\(key, val) -> " " <> key <> "=" <> val) dat
-
-logInfo, logErr :: MonadIO m => Text -> [(Text, Text)] -> m ()
-logInfo = log "INFO "
-logErr = log "ERROR"
-
advanceChain :: Machine -> [Value] -> Either (LangError Value) ([Value], Bindings (PrimFns Identity))
advanceChain chain vals =
let (r_, newSt) = runIdentity $ runLang (machineState chain) $ traverse eval vals
diff --git a/src/Radicle/Daemon/Logging.hs b/src/Radicle/Daemon/Logging.hs
new file mode 100644
index 0000000..41e4058
--- /dev/null
+++ b/src/Radicle/Daemon/Logging.hs
@@ -0,0 +1,59 @@
+-- | Functions for logging messages to @stdout@
+--
+-- All logging functions recive a message and a list of key-value pairs
+-- with additional info. This will be rendered as follows.
+--
+-- @
+-- logInfo "the message" [("foo", "5)]
+-- -- prints "INFO the message foo=5"
+-- @
+module Radicle.Daemon.Logging
+ ( LogLevel(..)
+ , MonadLog(..)
+ , logDebug
+ , logInfo
+ , logError
+ , logError'
+ ) where
+
+import Protolude hiding (log)
+
+data LogLevel = LogError | LogInfo | LogDebug
+ deriving (Eq, Ord)
+
+class (MonadIO m) => MonadLog m where
+ askLogLevel :: m LogLevel
+
+
+log :: MonadLog m => LogLevel -> Text -> [(Text, Text)] -> m ()
+log targetLevel msg info = do
+ currentLogLevel <- askLogLevel
+ if currentLogLevel >= targetLevel
+ then log' targetLevel msg info
+ else pure ()
+
+log' :: MonadIO m => LogLevel -> Text -> [(Text, Text)] -> m ()
+log' targetLevel msg info = do
+ putStrLn $ renderLogLevel targetLevel <> " " <> msg <> renderInfo
+ where
+ renderLogLevel :: LogLevel -> Text
+ renderLogLevel LogError = "ERROR"
+ renderLogLevel LogInfo = "INFO "
+ renderLogLevel LogDebug = "DEBUG"
+
+ renderInfo = foldMap (\(key, val) -> " " <> key <> "=" <> val) info
+
+
+logDebug :: MonadLog m => Text -> [(Text,Text)] -> m ()
+logDebug = log LogDebug
+
+logInfo :: MonadLog m => Text -> [(Text,Text)] -> m ()
+logInfo = log LogInfo
+
+logError :: MonadLog m => Text -> [(Text,Text)] -> m ()
+logError = log LogError
+
+-- | Similar to 'logError' but does not require a current log level.
+-- Always logs the error.
+logError' :: MonadIO m => Text -> [(Text,Text)] -> m ()
+logError' = log' LogError
diff --git a/src/Radicle/Daemon/Monad.hs b/src/Radicle/Daemon/Monad.hs
index d6b659e..cb49e7f 100644
--- a/src/Radicle/Daemon/Monad.hs
+++ b/src/Radicle/Daemon/Monad.hs
@@ -20,6 +20,7 @@ import Protolude
import Radicle (LangError, Value, renderCompactPretty)
import Radicle.Daemon.Common
import Radicle.Daemon.Ipfs
+import Radicle.Daemon.Logging
import Radicle.Ipfs
@@ -32,13 +33,13 @@ runDaemon env (Daemon x) = runReaderT (runExceptT x) env
liftExceptT :: (e -> Error) -> ExceptT e IO a -> Daemon a
liftExceptT makeError action = Daemon $ mapExceptT (lift . fmap (first makeError)) action
+instance MonadLog Daemon where
+ askLogLevel = asks logLevel
+
-- * Environment
type FileLock = MVar ()
-data LogLevel = Normal | Debug
- deriving (Eq, Ord)
-
data Env = Env
{ machineConfigFileLock :: FileLock
, machineConfigFile :: FilePath