Browse Source

Log InternalError must writes message to error file too

Volodymyr Tkach 2 years ago
parent
commit
fc33edc678
2 changed files with 35 additions and 1 deletions
  1. 7 1
      utils/http/logger/logger.go
  2. 28 0
      utils/http/logger/logger_test.go

+ 7 - 1
utils/http/logger/logger.go

@@ -49,7 +49,13 @@ func LogInfo(format string, a ...any) {
 }
 }
 
 
 func LogInternalError(err error) {
 func LogInternalError(err error) {
-	log.Printf("%s\n", err.Error())
+	msg := fmt.Sprintf("%s\n", err.Error())
+	log.Printf("%s", msg)
+	if ErrorLogFile != "" {
+		if err := appendToLogFile(ErrorLogFile, time.Now().Format("2006/01/02 15:04:05")+" "+msg); err != nil {
+			log.Printf("%s\n", err.Error())
+		}
+	}
 	if RollBarEnabled && !RollBarSkipErrors.contain(err.Error()) {
 	if RollBarEnabled && !RollBarSkipErrors.contain(err.Error()) {
 		rollbar.Error(err)
 		rollbar.Error(err)
 	}
 	}

+ 28 - 0
utils/http/logger/logger_test.go

@@ -6,6 +6,8 @@ import (
 	"log"
 	"log"
 	"net/http"
 	"net/http"
 	"net/http/httptest"
 	"net/http/httptest"
+	"os"
+	"strings"
 	"testing"
 	"testing"
 
 
 	. "github.com/onsi/ginkgo"
 	. "github.com/onsi/ginkgo"
@@ -14,6 +16,32 @@ import (
 )
 )
 
 
 var _ = Describe("logger", func() {
 var _ = Describe("logger", func() {
+	Context("LogInternalError", func() {
+		original := logger.ErrorLogFile
+		logger.ErrorLogFile = "/tmp/test-err-out.log"
+
+		f, err := os.OpenFile(logger.ErrorLogFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
+		Expect(err).To(Succeed())
+		_, err = fmt.Fprint(f, "")
+		Expect(err).To(Succeed())
+		Expect(f.Close()).To(Succeed())
+
+		logger.LogInternalError(fmt.Errorf("MyError 1"))
+		file, err := os.ReadFile(logger.ErrorLogFile)
+		Expect(err).To(Succeed())
+		content := string(file)
+		Expect(strings.HasSuffix(content, "MyError 1\n")).To(Equal(true))
+
+		logger.LogInternalError(fmt.Errorf("MyError 2"))
+		file, err = os.ReadFile(logger.ErrorLogFile)
+		Expect(err).To(Succeed())
+		content = string(file)
+		Expect(strings.HasSuffix(content, "MyError 2\n")).To(Equal(true))
+
+		// Restore original value
+		logger.ErrorLogFile = original
+	})
+
 	Context("LogRequests", func() {
 	Context("LogRequests", func() {
 		var srv *httptest.Server
 		var srv *httptest.Server
 		var client *http.Client
 		var client *http.Client