summary refs log tree commit diff
path: root/vendor/go.mau.fi/util/exzerolog/writer.go
blob: c5709853cdc18991e20e76b08e9afc3ba1fb35f2 (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
72
73
74
75
76
77
78
79
80
81
// Copyright (c) 2023 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package exzerolog

import (
	"bytes"
	"sync"

	"github.com/rs/zerolog"
)

// LogWriter wraps a zerolog.Logger and provides an io.Writer with buffering so each written line is logged separately.
type LogWriter struct {
	log   zerolog.Logger
	level zerolog.Level
	field string
	mu    sync.Mutex
	buf   bytes.Buffer
}

func NewLogWriter(log zerolog.Logger) *LogWriter {
	zerolog.Nop()
	return &LogWriter{
		log:   log,
		level: zerolog.DebugLevel,
		field: zerolog.MessageFieldName,
	}
}

func (lw *LogWriter) WithLevel(level zerolog.Level) *LogWriter {
	return &LogWriter{
		log:   lw.log,
		level: level,
		field: lw.field,
	}
}

func (lw *LogWriter) WithField(field string) *LogWriter {
	return &LogWriter{
		log:   lw.log,
		level: lw.level,
		field: field,
	}
}

func (lw *LogWriter) writeLine(data []byte) {
	if len(data) == 0 {
		return
	}
	if data[len(data)-1] == '\n' {
		data = data[:len(data)-1]
	}
	if lw.buf.Len() > 0 {
		lw.buf.Write(data)
		data = lw.buf.Bytes()
		lw.buf.Reset()
	}
	lw.log.WithLevel(lw.level).Bytes(lw.field, data).Send()
}

func (lw *LogWriter) Write(data []byte) (n int, err error) {
	lw.mu.Lock()
	defer lw.mu.Unlock()
	newline := bytes.IndexByte(data, '\n')
	if newline == len(data)-1 {
		lw.writeLine(data)
	} else if newline < 0 {
		lw.buf.Write(data)
	} else {
		lines := bytes.Split(data, []byte{'\n'})
		for _, line := range lines[:len(lines)-1] {
			lw.writeLine(line)
		}
		lw.buf.Write(lines[len(lines)-1])
	}
	return len(data), nil
}