github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/log/buffer.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package log 7 8 import ( 9 "bytes" 10 "sync" 11 ) 12 13 type bufferWriteCloser struct { 14 mu sync.Mutex 15 buffer bytes.Buffer 16 } 17 18 func (b *bufferWriteCloser) Write(p []byte) (int, error) { 19 b.mu.Lock() 20 defer b.mu.Unlock() 21 return b.buffer.Write(p) 22 } 23 24 func (b *bufferWriteCloser) Close() error { 25 return nil 26 } 27 28 func (b *bufferWriteCloser) String() string { 29 b.mu.Lock() 30 defer b.mu.Unlock() 31 return b.buffer.String() 32 } 33 34 // BufferLogger implements LoggerProvider and writes messages in a buffer. 35 type BufferLogger struct { 36 WriterLogger 37 } 38 39 // NewBufferLogger create BufferLogger returning as LoggerProvider. 40 func NewBufferLogger() LoggerProvider { 41 log := &BufferLogger{} 42 log.NewWriterLogger(&bufferWriteCloser{}) 43 return log 44 } 45 46 // Init inits connection writer 47 func (log *BufferLogger) Init(string) error { 48 log.NewWriterLogger(log.out) 49 return nil 50 } 51 52 // Content returns the content accumulated in the content provider 53 func (log *BufferLogger) Content() (string, error) { 54 return log.out.(*bufferWriteCloser).String(), nil 55 } 56 57 // Flush when log should be flushed 58 func (log *BufferLogger) Flush() { 59 } 60 61 // ReleaseReopen does nothing 62 func (log *BufferLogger) ReleaseReopen() error { 63 return nil 64 } 65 66 // GetName returns the default name for this implementation 67 func (log *BufferLogger) GetName() string { 68 return "buffer" 69 } 70 71 func init() { 72 Register("buffer", NewBufferLogger) 73 }