2020-03-10 02:57:53 +07:00
|
|
|
package logging
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2021-08-03 16:55:21 +07:00
|
|
|
|
|
|
|
"github.com/authelia/authelia/internal/configuration/schema"
|
2020-03-10 02:57:53 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestShouldWriteLogsToFile(t *testing.T) {
|
|
|
|
dir, err := ioutil.TempDir("/tmp", "logs-dir")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-03-10 02:57:53 +07:00
|
|
|
defer os.RemoveAll(dir)
|
|
|
|
|
|
|
|
path := fmt.Sprintf("%s/authelia.log", dir)
|
2021-08-03 16:55:21 +07:00
|
|
|
err = InitializeLogger(schema.LogConfiguration{Format: "text", FilePath: path, KeepStdout: false}, false)
|
2021-05-31 11:02:54 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
Logger().Info("This is a test")
|
|
|
|
|
|
|
|
f, err := os.OpenFile(path, os.O_RDONLY, 0)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(f)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
assert.Contains(t, string(b), "level=info msg=\"This is a test\"\n")
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestShouldWriteLogsToFileAndStdout(t *testing.T) {
|
|
|
|
dir, err := ioutil.TempDir("/tmp", "logs-dir")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer os.RemoveAll(dir)
|
|
|
|
|
|
|
|
path := fmt.Sprintf("%s/authelia.log", dir)
|
2021-08-03 16:55:21 +07:00
|
|
|
err = InitializeLogger(schema.LogConfiguration{Format: "text", FilePath: path, KeepStdout: true}, false)
|
2020-03-10 02:57:53 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
Logger().Info("This is a test")
|
|
|
|
|
|
|
|
f, err := os.OpenFile(path, os.O_RDONLY, 0)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(f)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
assert.Contains(t, string(b), "level=info msg=\"This is a test\"\n")
|
|
|
|
}
|
2020-11-25 06:46:41 +07:00
|
|
|
|
|
|
|
func TestShouldFormatLogsAsJSON(t *testing.T) {
|
|
|
|
dir, err := ioutil.TempDir("/tmp", "logs-dir")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer os.RemoveAll(dir)
|
|
|
|
|
|
|
|
path := fmt.Sprintf("%s/authelia.log", dir)
|
2021-08-03 16:55:21 +07:00
|
|
|
err = InitializeLogger(schema.LogConfiguration{Format: "json", FilePath: path, KeepStdout: false}, false)
|
2020-11-25 06:46:41 +07:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
Logger().Info("This is a test")
|
|
|
|
|
|
|
|
f, err := os.OpenFile(path, os.O_RDONLY, 0)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(f)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
assert.Contains(t, string(b), "{\"level\":\"info\",\"msg\":\"This is a test\",")
|
|
|
|
}
|