A peer-to-peer stack for code collaboration
Extract logging into separate module
Thomas Scholtes707002fc0708
diff --git a/exe/Daemon.hs b/exe/Daemon.hsindex 1f529c0..c83b1cd 100644--- a/exe/Daemon.hs+++ b/exe/Daemon.hs@@ -17,10 +17,10 @@ import Options.Applicativeimport Servantimport System.IO (BufferMode(..), hSetBuffering)-import Radicle.Daemon.Common hiding (logInfo)-import qualified Radicle.Daemon.Common as Common+import Radicle.Daemon.Commonimport qualified Radicle.Daemon.HttpApi as Apiimport Radicle.Daemon.Ipfs+import Radicle.Daemon.Loggingimport Radicle.Daemon.MachineConfigimport Radicle.Daemon.Monad@@ -34,7 +34,7 @@ import qualified Radicle.Internal.UUID as UUID-- * TypeslogDaemonError :: MonadIO m => Error -> m ()-logDaemonError (displayError -> (m, xs)) = logErr m xs+logDaemonError (displayError -> (m, xs)) = logError' m xs-- * Main@@ -87,7 +87,7 @@ main = doOpts{..} <- execParser =<< cliInfomachineConfigFileLock <- 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 machineConfigFileinitRes <- runDaemon env (init machineConfig)case initRes of@@ -97,19 +97,19 @@ main = doRight _ -> dopolling <- async $ initPolling envlet 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 appexc <- waitEitherCatchCancel polling servcase exc ofLeft (Left err) -> do- logErr "Polling failed with an exception" [("error", toS (displayException err))]+ logError' "Polling failed with an exception" [("error", toS (displayException err))]exitFailureLeft (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))]exitFailureRight (Right ()) -> do- logErr "Server stopped (this should not happen)" []+ logError' "Server stopped (this should not happen)" []exitFailureserver :: Env -> Server Api.DaemonApi@@ -155,7 +155,7 @@ newMachine :: Daemon Api.NewResponsenewMachine = doid <- ipfs createMachine CouldNotCreateMachinesub <- 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 subinsertNewMachine id (Cached m)actAsWriter m@@ -175,7 +175,7 @@ query id (Api.QueryRequest v) = docase fst <$> runIdentity $ runLang (machineState m) $ eval v ofLeft 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) = dorequestInput (machineSubscription m)Just (Cached Machine{ machineMode = Reader, ..}) -> requestInput machineSubscriptionJust (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) = dononce <- liftIO $ UUID.uuidasyncMsg <- 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 asyncMsgcase msg_ ofJust 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 = domsCMap <- asks machines@@ -280,7 +272,7 @@ initDaemonSubscription id =machineIpfs id $ initSubscription id logNonDecodableMsgwherelogNonDecodableMsg 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 = domodifyMachine 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 = dom <- loadMachine Reader idenv <- 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 mwhereonMsg :: Message -> Daemon ()@@ -421,7 +413,7 @@ newReader id = doinitReaderNoFail :: MachineId -> Daemon ()initReaderNoFail id = catchError (initAsReader id $> ()) $ \err -> dolet (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) : infost <- liftIO Time.getSystemTimeinsertNewMachine id (UninitialisedReader t)@@ -435,13 +427,13 @@ refreshAsReader id = modifyMachine id refresh(newIdx, is) <- machineIpfs id $ machineInputsFrom (machineId m) (Just currentIdx)if currentIdx == newIdxthen 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 = doenv <- 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)]whereid = machineId monMsg = \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 rswherewrite = 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 -> dodiff --git a/src/Radicle/Daemon/Common.hs b/src/Radicle/Daemon/Common.hsindex 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) whereimport Protolude hiding (log)import qualified Data.Aeson as A-import qualified Data.Text as Timport qualified Data.Time.Clock.System as Timeimport Radicle@@ -55,25 +52,6 @@ data CachedMachinenewtype 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 valsdiff --git a/src/Radicle/Daemon/Logging.hs b/src/Radicle/Daemon/Logging.hsnew file mode 100644index 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' LogErrordiff --git a/src/Radicle/Daemon/Monad.hs b/src/Radicle/Daemon/Monad.hsindex d6b659e..cb49e7f 100644--- a/src/Radicle/Daemon/Monad.hs+++ b/src/Radicle/Daemon/Monad.hs@@ -20,6 +20,7 @@ import Protoludeimport Radicle (LangError, Value, renderCompactPretty)import Radicle.Daemon.Commonimport Radicle.Daemon.Ipfs+import Radicle.Daemon.Loggingimport Radicle.Ipfs@@ -32,13 +33,13 @@ runDaemon env (Daemon x) = runReaderT (runExceptT x) envliftExceptT :: (e -> Error) -> ExceptT e IO a -> Daemon aliftExceptT makeError action = Daemon $ mapExceptT (lift . fmap (first makeError)) action+instance MonadLog Daemon where+ askLogLevel = asks logLevel+-- * Environmenttype FileLock = MVar ()-data LogLevel = Normal | Debug- deriving (Eq, Ord)-data Env = Env{ machineConfigFileLock :: FileLock, machineConfigFile :: FilePath