Skip to content

Commit

Permalink
feat(Logger): add register_printer
Browse files Browse the repository at this point in the history
  • Loading branch information
favonia committed Sep 21, 2023
1 parent fb70c6b commit 8d1d14c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Logger.ml
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,12 @@ struct
~init_backtrace:(get_backtrace())
~emit:(fun d -> emit (m d))
~fatal:(fun d -> fatal (m d))

let register_printer f =
Printexc.register_printer @@ function
| Effect.Unhandled (Emit diag) -> f (`Emit diag)
| Fatal diag -> f (`Fatal diag)
| _ -> None

let () = register_printer @@ fun _ -> Some "Unhandled asai effect/exception; use Asai.Logger.run"
end
10 changes: 10 additions & 0 deletions src/LoggerSigs.ml
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,14 @@ sig
@param emit The interceptor of non-fatal diagnostics. The default value is {!val:emit}.
@param fatal The interceptor of fatal diagnostics. The default value is {!val:fatal}. *)
val try_with : ?emit:(Code.t Diagnostic.t -> unit) -> ?fatal:(Code.t Diagnostic.t -> 'a) -> (unit -> 'a) -> 'a

val register_printer : ([ `Emit of Code.t Diagnostic.t | `Fatal of Code.t Diagnostic.t ] -> string option) -> unit
(** [register_printer f] registers a printer [p] via {!val:Printexc.register_printer} to convert unhandled internal effects and exceptions into strings for the OCaml runtime system to display them. The functor {!module:Logger.Make} always registers a simple printer to suggest using {!val:run}, but you can register new ones to override it. The return type of the printer [p] should return [Some s] where [s] is the resulting string, or [None] if it chooses not to convert a particular effect or exception. The registered printers are tried in reverse order until one of them returns [Some s] for some [s]; that is, the last registered printer is tried first. Note that this function is a wrapper of {!val:Printexc.register_printer} and all the registered printers (via this function or {!val:Printexc.register_printer}) are put into the same list.
The input type of the printer [p] is a variant representation of all internal effects and exceptions used in this module:
- [`Emit diag] corresponds to the effect triggered by {!val:emit}; and
- [`Fatal diag] corresponds to the exception triggered by {!val:fatal}.
Note: {!val:Diagnostic.string_of_text} can be handy for converting a message into a string.
*)
end

0 comments on commit 8d1d14c

Please sign in to comment.