// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package log
import (
"fmt"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type CallbackWriteCloser struct {
callback func([]byte, bool)
}
func (c CallbackWriteCloser) Write(p []byte) (int, error) {
c.callback(p, false)
return len(p), nil
func (c CallbackWriteCloser) Close() error {
c.callback(nil, true)
return nil
func TestBaseLogger(t *testing.T) {
var written []byte
var closed bool
c := CallbackWriteCloser{
callback: func(p []byte, close bool) {
written = p
closed = close
},
prefix := "TestPrefix "
b := WriterLogger{
out: c,
Level: INFO,
Flags: LstdFlags | LUTC,
Prefix: prefix,
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,
msg: "TEST MSG",
caller: "CALLER",
filename: "FULL/FILENAME",
line: 1,
time: date,
assert.Equal(t, INFO, b.GetLevel())
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.msg)
b.LogEvent(&event)
assert.Equal(t, expected, string(written))
assert.False(t, closed)
written = written[:0]
event.level = DEBUG
expected = ""
event.level = TRACE
event.level = WARN
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.msg)
event.level = ERROR
event.level = CRITICAL
b.Close()
assert.True(t, closed)
func TestBaseLoggerDated(t *testing.T) {
prefix := ""
Level: WARN,
Flags: Ldate | Ltime | Lmicroseconds | Lshortfile | Llevel,
date := time.Date(2019, time.January, 13, 22, 3, 30, 115, location)
dateString := date.Format("2006/01/02 15:04:05.000000")
level: WARN,
msg: "TEST MESSAGE TEST\n",
assert.Equal(t, WARN, b.GetLevel())
expected := fmt.Sprintf("%s%s %s:%d [%s] %s", prefix, dateString, "FILENAME", event.line, strings.ToUpper(event.level.String()), event.msg)
event.level = INFO
expected = fmt.Sprintf("%s%s %s:%d [%s] %s", prefix, dateString, "FILENAME", event.line, strings.ToUpper(event.level.String()), event.msg)
func TestBaseLoggerMultiLineNoFlagsRegexp(t *testing.T) {
Level: DEBUG,
StacktraceLevel: ERROR,
Flags: -1,
Expression: "FILENAME",
b.NewWriterLogger(c)
level: DEBUG,
msg: "TEST\nMESSAGE\nTEST",
assert.Equal(t, DEBUG, b.GetLevel())
expected := "TEST\n\tMESSAGE\n\tTEST\n"
event.filename = "ELSEWHERE"
assert.Equal(t, "", string(written))
event.caller = "FILENAME"
event = Event{
msg: "TEST\nFILENAME\nTEST",
filename: "FULL/ELSEWHERE",
expected = "TEST\n\tFILENAME\n\tTEST\n"
func TestBrokenRegexp(t *testing.T) {
Expression: "\\",
assert.Empty(t, b.regexp)