0

I'd like to trivially provide a mechanism for logging data using pretty prints rather than plain type->string conversions which doesn't interfere with data transfer through strings.

I can add a type.String() converter method - which will then automatically be used by the fmt library which is generally what is being used for logging output.

However, this is likely to interfere in other domains which use type->string conversion and default to using the .String() mechanic (maybe there is a better standard interface that should be used when "give me this thing as a scannable string" is desired?)

What is the "right Go way" or a practical approach for writing type->string converters which are intended for data I/O - such as HTTP URI params or database I/O etc., vs. pretty print to logs?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Mordachai
  • 9,412
  • 6
  • 60
  • 112
  • You can try implementing a `PrettyPrinter` where you can register type converters, so specific types can have different printers but all fall back to `fmt.Sprint()` – Burak Serdar Jan 16 '20 at 20:21
  • That requires an explicit call to every place I want it to print in a pretty manner, no? e.g. `fmt.Sptrintf("pretty printed value: %s", myThing.PrettyPrint())` no? I'm desiring the ability to provide the type.String() so that I can say fmt.Sprintf(myThing) and have it pretty-print - while still providing a separate mechanism for I/O that uses a simpler strconv.Itoa(mytype) --- I'm unclear on how to obtain this for my own user-types...? – Mordachai Jan 16 '20 at 20:26
  • 2
    IMHO if you want structured logging of some sort you shouldn't be using `fmt` and need another abstraction layer. For simple things however, I've use the `GoStringer` format for detailed logging, while leaving `Stringer` for anything that might be automatically converted elsewhere. – JimB Jan 16 '20 at 20:30
  • 1
    Why don't you use `json.Marshaler` or similar for your logs? – Jonathan Hall Jan 16 '20 at 20:45
  • json doesn't do much for - say - a custom money amount type. It's just an integer - so no value in Marshalling it. – Mordachai Jan 16 '20 at 21:56

0 Answers0