Create aff logging function

Hello,

how do you create log function that would run in aff monad, I tried:

affLog :: forall a. Show a => a -> Aff Unit
affLog item = makeAff \done -> do
  _ <- log (show item)
  done $ Canceler (mempty <$ unit)

But seems I’m failing to create noOp canceler

1 Like

Ok, I managed to solve it seconds later :smiley:

affLog :: forall a. Show a => a -> Aff Unit
affLog item = makeAff \done -> do
  _ <- log (show item)
  pure mempty

UPDATE:

I found bug in that implementation and also incorporated comment from @mhmdanas, I was not calling done callback, so finall is

affLog :: forall a. Show a => a -> Aff Unit
affLog item = makeAff \done -> do
  _ <- logShow item
  _ <- done (Right mempty)
  pure mempty
1 Like

Is there any reason that you did not use logShow from Effect.Class.Console?

2 Likes

Yes, I did not know it exists, thank you

2 Likes

@tino415 I think you misunderstood my suggestion. I believe that the function you’re trying to implement is a specialization of logShow, so you can just write logShow where you want to use affLog.

1 Like

Also, you don’t need all that boilerplate to convert Effect to Aff. There’s a simple function to do that: liftEffect. To be more precise, any type which has a MonadEffect instance can be lifted from an Effect using liftEffect. And since logShow requires a MonadEffect instance, any type which has a MonadEffect instance can use logShow directly, so you don’t even need liftEffect here!

Edit: as @jy14898 noted, I am speaking about Effect.Class.Console.logShow and not Effect.Console.logShow.

3 Likes

This did not work, but it worked with liftEffect thank you

affLog :: forall a. Show a => a -> Aff Unit
affLog = liftEffect <<< logShow
1 Like

Make sure you have the correct logShow imported: Effect.Class.Console logShow (and not the one from Effect.Console) as logShow from there should work on its own without lifting

3 Likes

Thank you, that worked

1 Like