Should Display or Debug be used to format errors logged in internal services?

At work, the discussion came up if we should be formatting errors in our logs for internal services using the Display trait or the Debug trait. In particular, if I'm using Display, is it possible that I miss out on details that would otherwise be shown if I used Debug?

If your logs are seen by end users, I think it's quite clear that Display should be used, but what about for internal services that are essentially only seen by the developers themselves?

If you go by the documentation of each trait, it suggests that you should always use Debug since it's for debugging which might contain information that is not included in Display:

from the Display documentation:

Display is similar to Debug, but Display is for user-facing output, and so cannot be derived.

and from Debug:

Debug should format the output in a programmer-facing, debugging context.

The Error trait itself is unfortunately not very helpful:

Errors must describe themselves through the Display and Debug traits.

1 Like

In my experience, the Debug format for Error implementors nearly always produces the internal structure of error types without regard for explaining what the error means. This might be fine when the error is an enum or a public struct, so you can expect it has fairly obvious names, but not in general.

IMO, the one correct way to record an error for human viewing is to use Display formatting, and also traverse its source() chain and print those errors too.

2 Likes

If by any chance you use anyhow, have a look at anyhow::Error - Display representations.

I think that's basically what anyhow prints with the debug format "{:?}", right?

That's been my experience.

I tend to output both...
"{:?}, {}", err, err

And, definitely what kpreid said :point_up:. I think it's the reqwests library that heavily chains errors. Occasionally I've been unable troubleshoot without including the source chain in the output.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.