summaryrefslogtreecommitdiffstats
path: root/modules/log/buffer.go
blob: 1eee2465f14eacb4c4fc908d1707b32424081262 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package log

import (
	"bytes"
	"sync"
)

type bufferWriteCloser struct {
	mu     sync.Mutex
	buffer bytes.Buffer
}

func (b *bufferWriteCloser) Write(p []byte) (int, error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.buffer.Write(p)
}

func (b *bufferWriteCloser) Close() error {
	return nil
}

func (b *bufferWriteCloser) String() string {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.buffer.String()
}

// BufferLogger implements LoggerProvider and writes messages in a buffer.
type BufferLogger struct {
	WriterLogger
}

// NewBufferLogger create BufferLogger returning as LoggerProvider.
func NewBufferLogger() LoggerProvider {
	log := &BufferLogger{}
	log.NewWriterLogger(&bufferWriteCloser{})
	return log
}

// Init inits connection writer
func (log *BufferLogger) Init(string) error {
	log.NewWriterLogger(log.out)
	return nil
}

// Content returns the content accumulated in the content provider
func (log *BufferLogger) Content() (string, error) {
	return log.out.(*bufferWriteCloser).String(), nil
}

// Flush when log should be flushed
func (log *BufferLogger) Flush() {
}

// ReleaseReopen does nothing
func (log *BufferLogger) ReleaseReopen() error {
	return nil
}

// GetName returns the default name for this implementation
func (log *BufferLogger) GetName() string {
	return "buffer"
}

func init() {
	Register("buffer", NewBufferLogger)
}