github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/xlog/lock_syncer.go (about)

     1  package xlog
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"sync"
     7  
     8  	"go.uber.org/zap/zapcore"
     9  )
    10  
    11  var _ zapcore.WriteSyncer = (*xLogLockSyncer)(nil)
    12  
    13  type xLogLockSyncer struct {
    14  	ctx       context.Context
    15  	outWriter io.WriteCloser
    16  	mu        sync.Mutex
    17  }
    18  
    19  // Sync implements zapcore.WriteSyncer.
    20  func (syncer *xLogLockSyncer) Sync() error {
    21  	return nil
    22  }
    23  
    24  // Write implements zapcore.WriteSyncer.
    25  func (syncer *xLogLockSyncer) Write(log []byte) (n int, err error) {
    26  	syncer.mu.Lock()
    27  	defer syncer.mu.Unlock()
    28  
    29  	select {
    30  	case <-syncer.ctx.Done():
    31  		return 0, io.EOF
    32  	default:
    33  	}
    34  
    35  	// TODO Implemented filters or hooks to pre-process logs.
    36  	return syncer.outWriter.Write(log)
    37  }
    38  
    39  func XLogLockSyncer(ctx context.Context, writer io.WriteCloser) zapcore.WriteSyncer {
    40  	if writer == nil || ctx == nil {
    41  		return nil
    42  	}
    43  	syncer := &xLogLockSyncer{
    44  		ctx:       ctx,
    45  		outWriter: writer,
    46  	}
    47  	return syncer
    48  }