summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/mattermost/mattermost-server/v6/shared/mlog/tlog.go
blob: ef8f6016a08c3be6af0f0ca5b17d3b9819f3e3cb (plain) (blame)
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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package mlog

import (
	"bytes"
	"io"
	"os"
	"sync"

	"github.com/mattermost/logr/v2"
	"github.com/mattermost/logr/v2/formatters"
	"github.com/mattermost/logr/v2/targets"
)

// AddWriterTarget adds a simple io.Writer target to an existing Logger.
// The `io.Writer` can be a buffer which is useful for testing.
// When adding a buffer to collect logs make sure to use `mlog.Buffer` which is
// a thread safe version of `bytes.Buffer`.
func AddWriterTarget(logger *Logger, w io.Writer, useJSON bool, levels ...Level) error {
	filter := logr.NewCustomFilter(levels...)

	var formatter logr.Formatter
	if useJSON {
		formatter = &formatters.JSON{EnableCaller: true}
	} else {
		formatter = &formatters.Plain{EnableCaller: true}
	}

	target := targets.NewWriterTarget(w)
	return logger.log.Logr().AddTarget(target, "_testWriter", filter, formatter, 1000)
}

// CreateConsoleTestLogger creates a logger for unit tests. Log records are output to `os.Stdout`.
// Logs can also be mirrored to the optional `io.Writer`.
func CreateConsoleTestLogger(useJSON bool, level Level) *Logger {
	logger, _ := NewLogger()

	filter := logr.StdFilter{
		Lvl:        level,
		Stacktrace: LvlPanic,
	}

	var formatter logr.Formatter
	if useJSON {
		formatter = &formatters.JSON{EnableCaller: true}
	} else {
		formatter = &formatters.Plain{EnableCaller: true}
	}

	target := targets.NewWriterTarget(os.Stdout)
	if err := logger.log.Logr().AddTarget(target, "_testcon", filter, formatter, 1000); err != nil {
		panic(err)
	}
	return logger
}

// Buffer provides a thread-safe buffer useful for logging to memory in unit tests.
type Buffer struct {
	buf bytes.Buffer
	mux sync.Mutex
}

func (b *Buffer) Read(p []byte) (n int, err error) {
	b.mux.Lock()
	defer b.mux.Unlock()
	return b.buf.Read(p)
}
func (b *Buffer) Write(p []byte) (n int, err error) {
	b.mux.Lock()
	defer b.mux.Unlock()
	return b.buf.Write(p)
}
func (b *Buffer) String() string {
	b.mux.Lock()
	defer b.mux.Unlock()
	return b.buf.String()
}