How can I better debug my code using logs and excecptions?
- cohen.avrahamOP
G-d willing
Hello guys,
I would like to ask you how can I log the commands I have in a specific function?
Thedebugand thetracecannot be used inside regular functions.
Basically, my issue is that I have a very long functions that maps fields from one structure to another with different types of values for the fields.
So, in many places inside the code we use Either Text {Correct Type}, and when the Text reached I don’t get any message about it, unless I am checking that using theisRightfunction.
Is there a way for me to know when Either is using the Left value automatically?Thanks
- bernhard
Could you show an example of code (ideally with a test script) where you would like or expect logging to happen?
The
traceortraceIdfunctions are probably what you are after. Egfoo : Optional Bar baz = case foo of Nothing -> Left (traceId "Received Nothing") Some bar -> Right barEvery time the Nothing/Left case is hit, you’ll get a log message “Received Nothing”. Outside the IDE, I believe these messages are at the DEBUG level so you’ll have to make sure to set the appropriate logging level.
- cohen.avraham
bernhard:you’ll have to make sure to set the appropriate logging level.
Where do I set this?
- cohen.avraham
G-d willing
how can I use
traceId "Received Nothing"inside a a regular function, for example:sampleFunction: Int -> Int sampleFunction num = let num2 = num + 2 num3 = num2 * 3 in num3I want to output a log line after the
num2 = num + 2, and then another log line after thenum3 = num2 * 3 - Gary_Verhaegen 1
Hi @cohen.avraham,
To understand
trace, it’s important to remember that Daml is a functional language: there is no “statement”; everything must return a value. This makes logging a bit awkward, especially outside ofdoblocks.The way the
tracefunction works around that it takes two arguments: what to log, and what to return. (traceIdis just a shorthand for atracecall that logs exactly what it returns.)So, in your case, you want to change the expression
num + 2such that it logs a message in addition to returning the value:sampleFunction: Int -> Int sampleFunction num = let num2 = (trace "here" (num + 2)) num3 = num2 * 3 in num3or even, since
tracereturns the value of its second argument:sampleFunction: Int -> Int sampleFunction num = (trace "here" (num + 2)) * 3