logs icon indicating copy to clipboard operation
logs copied to clipboard

Using error count to drive the exit-code when log level is quiet

Open mbarbin opened this issue 7 months ago • 2 comments

Hi and thanks for Logs!

I'm attempting to reuse this pattern from an example in logs.mli:

let main () =
  Logs.set_reporter (Logs_fmt.reporter ());
  ...
  exit (if Logs.err_count () > 0 then 1 else 0);
  ()

I added some machinery to configure the Logs config (e.g. level) from the program's CLI, and reduced this to the following example:

main.ml:

let logs_cmd =
  Command.make
    ~summary:"use the logs library"
    (let+ () = Log_cli.set_config () in
     Logs.app (fun m -> m "Hello app");
     Logs.err (fun m -> m "Hello err");
     Logs.warn (fun m -> m "Hello warn");
     Logs.info (fun m -> m "Hello info");
     Logs.debug (fun m -> m "Hello debug");
     Err.exit (if Logs.err_count () > 0 then 1 else 0))
;;

I think this is very close to a solution that would be 100% based on Logs+Cmdliner (hopefully the behavior I am witnessing doesn't come from my thin layer .. 🐵).

At any rate, I noticed the following:


By default app, err, and warn messages are enabled.

  $ ./main.exe logs
  Hello app
  main.exe: [ERROR] Hello err
  main.exe: [WARNING] Hello warn
  [1]

All messages are enabled in debug mode.

  $ ./main.exe logs --verbosity=debug
  Hello app
  main.exe: [ERROR] Hello err
  main.exe: [WARNING] Hello warn
  main.exe: [INFO] Hello info
  main.exe: [DEBUG] Hello debug
  [1]

In app mode, the errors are silenced.

  $ ./main.exe logs --verbosity=app
  Hello app
  [1]

When in quiet mode, all outputs are silenced.

  $ ./main.exe logs --verbosity=quiet

And we note that the exit code is [0].

All seems well and excepted to me - except the very last bit:

And we note that the exit code is [0].

On one hand I can see that having a failing exit code when the output is free of errors can be surprising, but on the other hand I'm surprised that changing the log level can have an impact on the result of the execution. I was thinking about proposing a parallel with grep -q.

What do you think?

mbarbin avatar May 09 '25 18:05 mbarbin

Indeed that looks broken.

I just had a quick look, I think we just need to add the warn/error increment here.

dbuenzli avatar May 09 '25 20:05 dbuenzli

Indeed that looks broken.

OK, I'd be in favor of making the change then.

In light of this I'll change my pp-wrapper to align with this new behavior (at the moment I aligned it to the behavior of the current logs with respect to error-count vs log levels).

Thanks!

mbarbin avatar May 10 '25 07:05 mbarbin

Thank you for the fix!

mbarbin avatar Jul 08 '25 20:07 mbarbin

You are welcome. I had forgotten about the lwt backend though which replicates the logic. This is now done in b797648

dbuenzli avatar Jul 08 '25 21:07 dbuenzli