ca81fac41851633c6b7cefdea92dfb3e1e011575 — Victor Freire 4 months ago a251b3b
article: writing-logs-to-multiple-outputs-in-go
1 files changed, 23 insertions(+), 0 deletions(-)

M content-org/content.org
M content-org/content.org => content-org/content.org +23 -0
@@ 5415,6 5415,29 @@ mkShell {
  haven't used none of them, there's nothing like [[https://doc.rust-lang.org/cargo/][cargo]] or [[https://www.npmjs.com/][npm]] with a
  public registry and standardized /manifest/.

** Writing logs to multiple outputs in Go                               :go:
:EXPORT_DATE: 2023-07-19
:EXPORT_FILE_NAME: writing-logs-to-multiple-outputs-in-go
:EXPORT_HUGO_SLUG: writing-logs-to-multiple-outputs-in-go

The [[https://golang.org/pkg/io/#Writer][io.Writer]] interface is one of the most important interfaces in [[https://go.dev][Go]].
We can take advantage of it to write logs to multiple places at the
same time using the [[https://golang.org/pkg/io/#MultiWriter][io.MultiWriter]] function.

For example, writing a log to the Standard Output ([[https://golang.org/pkg/os/#pkg-variables][os.Stdout]] and a
file [[https://golang.org/pkg/os/#File][os.File]]) is pretty straightforward.

#+begin_src go
f, _ := os.Create("log.txt")
defer f.Close()

// our writer
w := io.MultiWriter(os.Stdout, f)
logger := log.New(w, "MultiWriter loggger", log.LstdFlags)

* Footnotes

[fn:48] [[https://www.polyml.org/][Poly/ML]] exposes a function that does just that: [[https://www.polyml.org/documentation/Reference/PolyMLStructure.html#print][PolyML.print]].