github.com/blend/go-sdk@v1.20220411.3/logger/interlocked_writer.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package logger
     9  
    10  import (
    11  	"io"
    12  	"sync"
    13  )
    14  
    15  // NewInterlockedWriter returns a new interlocked writer.
    16  func NewInterlockedWriter(output io.Writer) *InterlockedWriter {
    17  	if typed, ok := output.(*InterlockedWriter); ok {
    18  		return typed
    19  	}
    20  	return &InterlockedWriter{
    21  		Output: output,
    22  	}
    23  }
    24  
    25  // InterlockedWriter is a writer that serializes access to the Write() method.
    26  type InterlockedWriter struct {
    27  	sync.Mutex
    28  
    29  	Output io.Writer
    30  }
    31  
    32  // Write writes the given bytes to the inner writer.
    33  func (iw *InterlockedWriter) Write(buffer []byte) (count int, err error) {
    34  	iw.Lock()
    35  
    36  	count, err = iw.Output.Write(buffer)
    37  	if err != nil {
    38  		iw.Unlock()
    39  		return
    40  	}
    41  
    42  	iw.Unlock()
    43  	return
    44  }
    45  
    46  // Close closes any outputs that are io.WriteCloser's.
    47  func (iw *InterlockedWriter) Close() (err error) {
    48  	iw.Lock()
    49  	defer iw.Unlock()
    50  
    51  	if typed, isTyped := iw.Output.(io.WriteCloser); isTyped {
    52  		err = typed.Close()
    53  		if err != nil {
    54  			return
    55  		}
    56  	}
    57  	return
    58  }