Logging to a file or buffer in Go instead of `os.Stdout`

Logging to a file or buffer in Go instead of `os.Stdout`

Most logging packages allow you to specify a stream, buffer, or file to write to.

Here's an example of Google's go-logging package that lets you set a backend (set to os.Stdout below)

import ( "fmt" "os" "time" "http://ift.tt/2kp4zmS; ) var format = logging.MustStringFormatter( fmt.Sprintf( "%v %v", "%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s}", "%{id:03x}%{color:reset} %{message}", ), ) var backend = logging.NewBackendFormatter( logging.NewLogBackend(os.Stdout, "", 0), format) logging.SetBackend(backend) 

My problem is that when running go test, it executes my actual Go code which logs a whole bunch of stuff to stdout in various places.

Just for the purposes of my tests, I'd love to swap out Stdout for something else, like a file or text buffer. I'd also love to be able to read from that buffer so I can validate output for certain functions.

Problem is, I'm new to Go and I have no idea how to do that!

Is there a standard (i.e. commonly accepted) way to mock an output stream or a buffer?


Submitted August 11, 2017 at 02:02PM by lefthandpisces
via reddit http://ift.tt/2vsiC0Y


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s