Skip to content

Commit bbf637f

Browse files
Refactor PrintLog with log context
1 parent 09f046d commit bbf637f

File tree

6 files changed

+68
-29
lines changed

6 files changed

+68
-29
lines changed

bot-plutus-interface.cabal

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ test-suite bot-plutus-interface-test
175175
, data-default-class
176176
, either
177177
, extra
178+
, prettyprinter
178179
, filepath
179180
, freer-extras
180181
, freer-simple

src/BotPlutusInterface/Balance.hs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ module BotPlutusInterface.Balance (
77
) where
88

99
import BotPlutusInterface.CardanoCLI qualified as CardanoCLI
10-
import BotPlutusInterface.Effects (PABEffect, createDirectoryIfMissingCLI, printLog)
10+
import BotPlutusInterface.Effects (PABEffect, createDirectoryIfMissingCLI, printBpiLog)
1111
import BotPlutusInterface.Files (DummyPrivKey, unDummyPrivateKey)
1212
import BotPlutusInterface.Files qualified as Files
1313
import BotPlutusInterface.Types (LogLevel (Debug), PABConfig)
@@ -60,6 +60,7 @@ import Plutus.V1.Ledger.Api (
6060
)
6161

6262
import BotPlutusInterface.BodyBuilder qualified as BodyBuilder
63+
import Prettyprinter (pretty, viaShow, (<+>))
6364
import Prelude
6465

6566
{- | Collect necessary tx inputs and collaterals, add minimum lovelace values and balance non ada
@@ -86,7 +87,7 @@ balanceTxIO pabConf ownPkh unbalancedTx =
8687
(unBalancedTxValidityTimeRange unbalancedTx)
8788
(unBalancedTxTx unbalancedTx)
8889

89-
lift $ printLog @w Debug $ show utxoIndex
90+
lift $ printBpiLog @w Debug $ viaShow utxoIndex
9091

9192
-- We need this folder on the CLI machine, which may not be the local machine
9293
lift $ createDirectoryIfMissingCLI @w False (Text.unpack pabConf.pcTxFileDir)
@@ -130,7 +131,7 @@ balanceTxIO pabConf ownPkh unbalancedTx =
130131

131132
let minUtxos = prevMinUtxos ++ nextMinUtxos
132133

133-
lift $ printLog @w Debug $ "Min utxos: " ++ show minUtxos
134+
lift $ printBpiLog @w Debug $ "Min utxos:" <+> pretty minUtxos
134135

135136
-- Calculate fees by pre-balancing the tx, building it, and running the CLI on result
136137
txWithoutFees <-
@@ -142,7 +143,7 @@ balanceTxIO pabConf ownPkh unbalancedTx =
142143

143144
let fees = nonBudgettedFees + getBudgetPrice (getExecutionUnitPrices pabConf) exBudget
144145

145-
lift $ printLog @w Debug $ "Fees: " ++ show fees
146+
lift $ printBpiLog @w Debug $ "Fees:" <+> pretty fees
146147

147148
-- Rebalance the initial tx with the above fees
148149
balancedTx <- hoistEither $ balanceTxStep minUtxos utxoIndex changeAddr $ tx `withFee` fees

src/BotPlutusInterface/Contract.hs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import BotPlutusInterface.Effects (
1616
handleContractLog,
1717
handlePABEffect,
1818
logToContract,
19-
printLog,
19+
printBpiLog,
2020
queryChainIndex,
2121
readFileTextEnvelope,
2222
saveBudget,
@@ -164,7 +164,7 @@ handlePABReq ::
164164
PABReq ->
165165
Eff effs PABResp
166166
handlePABReq contractEnv req = do
167-
printLog @w Debug $ show req
167+
printBpiLog @w Debug $ pretty req
168168
resp <- case req of
169169
----------------------
170170
-- Handled requests --
@@ -200,7 +200,7 @@ handlePABReq contractEnv req = do
200200
-- YieldUnbalancedTxReq UnbalancedTx
201201
unsupported -> error ("Unsupported PAB effect: " ++ show unsupported)
202202

203-
printLog @w Debug $ show resp
203+
printBpiLog @w Debug $ pretty resp
204204
pure resp
205205

206206
awaitTxStatusChange ::
@@ -217,7 +217,7 @@ awaitTxStatusChange contractEnv txId = do
217217
case mTx of
218218
Nothing -> pure Unknown
219219
Just txState -> do
220-
printLog @w Debug $ "Found transaction in node, waiting " ++ show chainConstant ++ " blocks for it to settle."
220+
printBpiLog @w Debug $ "Found transaction in node, waiting" <+> pretty chainConstant <+> " blocks for it to settle."
221221
awaitNBlocks @w contractEnv (chainConstant + 1)
222222
-- Check if the tx is still present in chain-index, in case of a rollback
223223
-- we might not find it anymore.
@@ -292,10 +292,10 @@ writeBalancedTx contractEnv (Right tx) = do
292292
if signable
293293
then newEitherT $ CardanoCLI.signTx @w pabConf tx requiredSigners
294294
else
295-
lift . printLog @w Warn . Text.unpack . Text.unlines $
295+
lift . printBpiLog @w Warn . PP.vsep $
296296
[ "Not all required signatures have signing key files. Please sign and submit the tx manually:"
297-
, "Tx file: " <> Files.txFilePath pabConf "raw" (Tx.txId tx)
298-
, "Signatories (pkh): " <> Text.unwords (map pkhToText requiredSigners)
297+
, "Tx file:" <+> pretty (Files.txFilePath pabConf "raw" (Tx.txId tx))
298+
, "Signatories (pkh):" <+> pretty (Text.unwords (map pkhToText requiredSigners))
299299
]
300300

301301
when (not pabConf.pcDryRun && signable) $ do

src/BotPlutusInterface/Effects.hs

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ module BotPlutusInterface.Effects (
1414
uploadDir,
1515
updateInstanceState,
1616
printLog,
17+
printBpiLog,
1718
handleContractLog,
1819
logToContract,
1920
readFileTextEnvelope,
@@ -32,6 +33,7 @@ import BotPlutusInterface.Types (
3233
CLILocation (..),
3334
ContractEnvironment,
3435
ContractState (ContractState),
36+
LogContext (BpiLog, ContractLog),
3537
LogLevel (..),
3638
TxBudget,
3739
TxFile,
@@ -60,7 +62,8 @@ import Ledger qualified
6062
import Plutus.Contract.Effects (ChainIndexQuery, ChainIndexResponse)
6163
import Plutus.PAB.Core.ContractInstance.STM (Activity)
6264
import PlutusTx.Builtins.Internal (BuiltinByteString (BuiltinByteString))
63-
import Prettyprinter (Pretty (pretty), defaultLayoutOptions, layoutPretty)
65+
import Prettyprinter (Pretty (pretty), defaultLayoutOptions, layoutPretty, (<+>))
66+
import Prettyprinter qualified as PP
6467
import Prettyprinter.Render.String qualified as Render
6568
import System.Directory qualified as Directory
6669
import System.Exit (ExitCode (ExitFailure, ExitSuccess))
@@ -81,7 +84,7 @@ data PABEffect (w :: Type) (r :: Type) where
8184
CreateDirectoryIfMissing :: Bool -> FilePath -> PABEffect w ()
8285
-- Same as above but creates folder on the CLI machine, be that local or remote.
8386
CreateDirectoryIfMissingCLI :: Bool -> FilePath -> PABEffect w ()
84-
PrintLog :: LogLevel -> String -> PABEffect w ()
87+
PrintLog :: LogContext -> LogLevel -> PP.Doc () -> PABEffect w ()
8588
UpdateInstanceState :: Activity -> PABEffect w ()
8689
LogToContract :: (ToJSON w, Monoid w) => w -> PABEffect w ()
8790
ThreadDelay :: Int -> PABEffect w ()
@@ -123,7 +126,7 @@ handlePABEffect contractEnv =
123126
case contractEnv.cePABConfig.pcCliLocation of
124127
Local -> Directory.createDirectoryIfMissing createParents filePath
125128
Remote ipAddr -> createDirectoryIfMissingRemote ipAddr createParents filePath
126-
PrintLog logLevel txt -> printLog' contractEnv.cePABConfig.pcLogLevel logLevel txt
129+
PrintLog logCtx logLevel txt -> printLog' contractEnv.cePABConfig.pcLogLevel logCtx logLevel txt
127130
UpdateInstanceState s -> do
128131
atomically $
129132
modifyTVar contractEnv.ceContractState $
@@ -154,20 +157,25 @@ handlePABEffect contractEnv =
154157
SaveBudget txId exBudget -> saveBudgetImpl contractEnv txId exBudget
155158
)
156159

157-
printLog' :: LogLevel -> LogLevel -> String -> IO ()
158-
printLog' logLevelSetting msgLogLvl msg =
159-
when (logLevelSetting >= msgLogLvl) $ putStrLn msg
160+
printLog' :: LogLevel -> LogContext -> LogLevel -> PP.Doc () -> IO ()
161+
printLog' logLevelSetting msgCtx msgLogLvl msg =
162+
when (logLevelSetting >= msgLogLvl) $ putStrLn target
163+
where
164+
target =
165+
Render.renderString . layoutPretty defaultLayoutOptions $
166+
pretty msgCtx <+> pretty msgLogLvl <+> msg
160167

161168
-- | Reinterpret contract logs to be handled by PABEffect later down the line.
162169
handleContractLog :: forall w a effs. Member (PABEffect w) effs => Pretty a => Eff (LogMsg a ': effs) ~> Eff effs
163170
handleContractLog x = subsume $ handleContractLogInternal @w x
164171

165172
handleContractLogInternal :: forall w a effs. Pretty a => Eff (LogMsg a ': effs) ~> Eff (PABEffect w ': effs)
166173
handleContractLogInternal = reinterpret $ \case
167-
LMessage msg ->
168-
let msgLogLevel = toNativeLogLevel (msg ^. Freer.logLevel)
169-
msgPretty = Render.renderString . layoutPretty defaultLayoutOptions . pretty $ msg
170-
in printLog @w msgLogLevel msgPretty
174+
LMessage logMsg ->
175+
let msgContent = logMsg ^. Freer.logMessageContent
176+
msgLogLevel = toNativeLogLevel (logMsg ^. Freer.logLevel)
177+
msgPretty = pretty msgContent
178+
in printLog @w ContractLog msgLogLevel msgPretty
171179
where
172180
toNativeLogLevel Freer.Debug = Debug
173181
toNativeLogLevel Freer.Info = Info
@@ -247,12 +255,21 @@ createDirectoryIfMissingCLI ::
247255
createDirectoryIfMissingCLI createParents path = send @(PABEffect w) $ CreateDirectoryIfMissingCLI createParents path
248256

249257
printLog ::
258+
forall (w :: Type) (effs :: [Type -> Type]).
259+
Member (PABEffect w) effs =>
260+
LogContext ->
261+
LogLevel ->
262+
PP.Doc () ->
263+
Eff effs ()
264+
printLog logCtx logLevel msg = send @(PABEffect w) $ PrintLog logCtx logLevel msg
265+
266+
printBpiLog ::
250267
forall (w :: Type) (effs :: [Type -> Type]).
251268
Member (PABEffect w) effs =>
252269
LogLevel ->
253-
String ->
270+
PP.Doc () ->
254271
Eff effs ()
255-
printLog logLevel msg = send @(PABEffect w) $ PrintLog logLevel msg
272+
printBpiLog = printLog @w BpiLog
256273

257274
updateInstanceState ::
258275
forall (w :: Type) (effs :: [Type -> Type]). Member (PABEffect w) effs => Activity -> Eff effs ()

src/BotPlutusInterface/Types.hs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ module BotPlutusInterface.Types (
77
CLILocation (..),
88
AppState (AppState),
99
LogLevel (..),
10+
LogContext (..),
1011
ContractEnvironment (..),
1112
Tip (Tip, epoch, hash, slot, block, era, syncProgress),
1213
ContractState (..),
@@ -53,6 +54,7 @@ import Plutus.PAB.Effects.Contract.Builtin (
5354
SomeBuiltin (SomeBuiltin),
5455
endpointsToSchemas,
5556
)
57+
import Prettyprinter (Pretty (pretty))
5658
import Servant.Client (BaseUrl (BaseUrl), Scheme (Http))
5759
import Wallet.Types (ContractInstanceId (..))
5860
import Prelude
@@ -184,7 +186,23 @@ data CLILocation = Local | Remote Text
184186
deriving stock (Show, Eq)
185187

186188
data LogLevel = Error | Warn | Notice | Info | Debug
187-
deriving stock (Eq, Ord, Show)
189+
deriving stock (Bounded, Enum, Eq, Ord, Show)
190+
191+
instance Pretty LogLevel where
192+
pretty = \case
193+
Debug -> "[DEBUG]"
194+
Info -> "[INFO]"
195+
Notice -> "[NOTICE]"
196+
Warn -> "[WARNING]"
197+
Error -> "[ERROR]"
198+
199+
data LogContext = BpiLog | ContractLog
200+
deriving stock (Bounded, Enum, Eq, Ord, Show)
201+
202+
instance Pretty LogContext where
203+
pretty = \case
204+
BpiLog -> "[BPI]"
205+
ContractLog -> "[CONTRACT]"
188206

189207
instance Default PABConfig where
190208
def =

test/Spec/MockContract.hs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import BotPlutusInterface.Types (
5555
BudgetEstimationError,
5656
ContractEnvironment (..),
5757
ContractState (ContractState, csActivity, csObservableState),
58+
LogContext,
5859
LogLevel (..),
5960
PABConfig (..),
6061
TxBudget (TxBudget),
@@ -125,6 +126,7 @@ import Plutus.PAB.Core.ContractInstance.STM (Activity (Active))
125126
import Plutus.V1.Ledger.Credential (Credential (PubKeyCredential))
126127
import PlutusTx.Builtins (fromBuiltin)
127128
import PlutusTx.Builtins.Internal (BuiltinByteString (BuiltinByteString))
129+
import Prettyprinter qualified as PP
128130
import System.IO.Unsafe (unsafePerformIO)
129131
import Text.Read (readMaybe)
130132
import Wallet.Types (ContractInstanceId (ContractInstanceId))
@@ -208,7 +210,7 @@ data MockContractState w = MockContractState
208210
, _commandHistory :: [Text]
209211
, _instanceUpdateHistory :: [Activity]
210212
, _observableState :: w
211-
, _logHistory :: [(LogLevel, String)]
213+
, _logHistory :: [(LogContext, LogLevel, PP.Doc ())]
212214
, _contractEnv :: ContractEnvironment w
213215
, _utxos :: [(TxOutRef, TxOut)]
214216
, _tip :: Tip
@@ -292,7 +294,7 @@ runPABEffectPure initState req =
292294
mockCreateDirectoryIfMissing createParents filePath
293295
go (CreateDirectoryIfMissingCLI createParents filePath) =
294296
mockCreateDirectoryIfMissing createParents filePath
295-
go (PrintLog logLevel msg) = mockPrintLog logLevel msg
297+
go (PrintLog logCtx logLevel msg) = mockPrintLog logCtx logLevel msg
296298
go (UpdateInstanceState msg) = mockUpdateInstanceState msg
297299
go (LogToContract msg) = mockLogToContract msg
298300
go (ThreadDelay microseconds) = mockThreadDelay microseconds
@@ -454,9 +456,9 @@ valueToUtxoOut =
454456
mockCreateDirectoryIfMissing :: forall (w :: Type). Bool -> FilePath -> MockContract w ()
455457
mockCreateDirectoryIfMissing _ _ = pure ()
456458

457-
mockPrintLog :: forall (w :: Type). LogLevel -> String -> MockContract w ()
458-
mockPrintLog logLevel msg =
459-
modify @(MockContractState w) (logHistory %~ ((logLevel, msg) <|))
459+
mockPrintLog :: forall (w :: Type). LogContext -> LogLevel -> PP.Doc () -> MockContract w ()
460+
mockPrintLog logCtx logLevel msg =
461+
modify @(MockContractState w) (logHistory %~ ((logCtx, logLevel, msg) <|))
460462

461463
mockUpdateInstanceState :: forall (w :: Type). Activity -> MockContract w ()
462464
mockUpdateInstanceState msg =

0 commit comments

Comments
 (0)