Skip to content
CCPEDIAby Unity Nodes
App Development

How can I better debug my code using logs and excecptions?

5 posts269 views1 likesLast activity May 2022

  1. 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?
    The debug and the trace cannot 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 the isRight function.
    Is there a way for me to know when Either is using the Left value automatically?

    Thanks

  2. bernhard

    Could you show an example of code (ideally with a test script) where you would like or expect logging to happen?

    The trace or traceId functions are probably what you are after. Eg

    foo : Optional Bar
    baz = case foo of
      Nothing -> Left (traceId "Received Nothing")
      Some bar -> Right bar
    

    Every 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.

  3. cohen.avraham
    bernhard:

    you’ll have to make sure to set the appropriate logging level.

    Where do I set this?

  4. 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
      num3 
    
    

    I want to output a log line after the num2 = num + 2, and then another log line after the num3 = num2 * 3

  5. 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 of do blocks.

    The way the trace function works around that it takes two arguments: what to log, and what to return. (traceId is just a shorthand for a trace call that logs exactly what it returns.)

    So, in your case, you want to change the expression num + 2 such 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
      num3
    

    or even, since trace returns the value of its second argument:

    sampleFunction: Int -> Int
    sampleFunction num =
      (trace "here" (num + 2)) * 3