Logging to Console in PureScript

by|inArticles||2 min read

Logging in a strictly typed programming language like PureScript do not work as simple as in JavaScript. Or does it?

Logging with Effect.Console

The basic way is to use the log method from puresript-console package.

import Effect.Console (log)

main :: Unit
main = do
  log "This will be shown in the console"

Two things are to mention here:

  1. This method is effectful (Effect Unit)
  2. This method expects a String. This means if you would like to log complex objects, you need to transform them to String yourself.

For the second point we can replace the log function with the logShow function. The difference is that the data structure you will log, need to be part of the Show typeclass (hence, probably implement or derive the show method).

Logging with Debug

Many would find the solution above and stop here. In many cases it is sufficient, it is not wrong to do so.

Another way is the purescript-debug package. Here you can find the traceM function. This differs in two ways from the log function above:

  1. The constraint is monadic, so it can be used in any monad, not only Effect (but as well in Effect).
  2. The data structure to log has no limitation. We can pass a string or a whole data structure without implementing Show.

Here is an example how to log in PureScript with debug:

import Debug (traceM)

main :: Unit
main = do
  traceM thing
  thing = { name: "Test", purpose: "Logging" }

It is on you to decide what you prefer, another dependency in your project or the ease of use of traceM. 

Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

© Copyright 2024 - ersocon.net - All rights reservedVer. 415