summaryrefslogtreecommitdiffstats
path: root/modules/log/event_writer_conn_test.go
blob: de8694f2c5f05bcbbb8f882724f7d11783df642e (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
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package log

import (
	"context"
	"fmt"
	"io"
	"net"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func listenReadAndClose(t *testing.T, l net.Listener, expected string) {
	conn, err := l.Accept()
	require.NoError(t, err)
	defer conn.Close()
	written, err := io.ReadAll(conn)

	require.NoError(t, err)
	assert.Equal(t, expected, string(written))
}

func TestConnLogger(t *testing.T) {
	protocol := "tcp"
	address := ":3099"

	l, err := net.Listen(protocol, address)
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()

	prefix := "TestPrefix "
	level := INFO
	flags := LstdFlags | LUTC | Lfuncname

	logger := NewLoggerWithWriters(context.Background(), "test", NewEventWriterConn("test-conn", WriterMode{
		Level:        level,
		Prefix:       prefix,
		Flags:        FlagsFromBits(flags),
		WriterOption: WriterConnOption{Addr: address, Protocol: protocol, Reconnect: true, ReconnectOnMsg: true},
	}))

	location, _ := time.LoadLocation("EST")

	date := time.Date(2019, time.January, 13, 22, 3, 30, 15, location)

	dateString := date.UTC().Format("2006/01/02 15:04:05")

	event := Event{
		Level:         INFO,
		MsgSimpleText: "TEST MSG",
		Caller:        "CALLER",
		Filename:      "FULL/FILENAME",
		Line:          1,
		Time:          date,
	}
	expected := fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.Filename, event.Line, event.Caller, strings.ToUpper(event.Level.String())[0], event.MsgSimpleText)
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		listenReadAndClose(t, l, expected)
	}()
	logger.SendLogEvent(&event)
	wg.Wait()

	logger.Close()
}