The log
package uses an internal buffer to build-up log messages for output (the buf
field in log/Logger). It composes the header, appends the data provided by the caller, then passes this buffer to your Write
method for output.
In order to reduce allocations, the log
package recycles this buffer for each log message. It's not stated in the documentation, but the implicit assumption is that your Write
method only uses the provided []byte
data for the duration of the Write
call. This assumption is OK for most outputs, e.g. a file or STDOUT.
To avoid a data race, you need to make an explicit copy of the incoming data before returning from the Write
function:
func (f LogBuffer) Write(b []byte) (n int, err error) {
z := make([]byte, len(b))
copy(z, b)
f.LogInputChan <- z
return len(b), nil
}