Create log folder if not present

This commit is contained in:
tanyadegurechaff 2017-04-28 00:36:04 +09:00 committed by Emile Vauge
parent c1220b8765
commit 987ae92f53
3 changed files with 29 additions and 13 deletions

View file

@ -7,6 +7,7 @@ import (
fmtlog "log"
"net/http"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
@ -206,6 +207,13 @@ func run(traefikConfiguration *server.TraefikConfiguration) {
}
log.SetLevel(level)
if len(globalConfiguration.TraefikLogsFile) > 0 {
dir := filepath.Dir(globalConfiguration.TraefikLogsFile)
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Errorf("Failed to create log path %s: %s", dir, err)
}
fi, err := os.OpenFile(globalConfiguration.TraefikLogsFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
defer func() {
if err := fi.Close(); err != nil {

View file

@ -7,6 +7,7 @@ import (
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
@ -54,6 +55,13 @@ type logInfoResponseWriter struct {
// NewLogger returns a new Logger instance.
func NewLogger(file string) *Logger {
if len(file) > 0 {
dir := filepath.Dir(file)
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Errorf("Failed to create log path %s: %s", dir, err)
}
fi, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Error("Error opening file", err)

View file

@ -7,7 +7,6 @@ import (
"net/url"
"os"
"path/filepath"
"runtime"
"testing"
shellwords "github.com/mattn/go-shellwords"
@ -18,8 +17,7 @@ type logtestResponseWriter struct{}
var (
logger *Logger
logfileName = "traefikTestLogger.log"
logfilePath string
logfileNameSuffix = "/traefik/logger/test.log"
helloWorld = "Hello, World"
testBackendName = "http://127.0.0.1/testBackend"
testFrontendName = "testFrontend"
@ -39,14 +37,21 @@ var (
)
func TestLogger(t *testing.T) {
if runtime.GOOS == "windows" {
logfilePath = filepath.Join(os.Getenv("TEMP"), logfileName)
} else {
logfilePath = filepath.Join("/tmp", logfileName)
tmp, err := ioutil.TempDir("", "testlogger")
if err != nil {
t.Fatalf("failed to create temp dir: %s", err)
}
defer os.RemoveAll(tmp)
logfilePath := filepath.Join(tmp, logfileNameSuffix)
logger = NewLogger(logfilePath)
defer cleanup()
defer logger.Close()
if _, err := os.Stat(logfilePath); os.IsNotExist(err) {
t.Fatalf("logger should create %s", logfilePath)
}
SetBackend2FrontendMap(&testBackend2FrontendMap)
r := &http.Request{
@ -86,11 +91,6 @@ func TestLogger(t *testing.T) {
}
}
func cleanup() {
logger.Close()
os.Remove(logfilePath)
}
func printLogdata(logdata []byte) string {
return fmt.Sprintf(
"\nExpected: %s\n"+