Add unit tests for custom log formatter

Also moved is Colorful check to WriteMsg function to make the interface for user's using the custom logging formatting simpler. The user does not have to check if the text is colorful now, the WriteMsg function handles it.
This commit is contained in:
IamCathal 2020-09-09 00:23:57 +01:00
parent 0189e6329a
commit 8982f5d702
2 changed files with 39 additions and 7 deletions

View File

@ -58,10 +58,6 @@ type consoleWriter struct {
func (c *consoleWriter) Format(lm *LogMsg) string {
msg := lm.Msg
if c.Colorful {
msg = strings.Replace(lm.Msg, levelPrefix[lm.Level], colors[lm.Level](levelPrefix[lm.Level]), 1)
}
h, _, _ := formatTimeHeader(lm.When)
bytes := append(append(h, msg...), '\n')
@ -105,13 +101,13 @@ func (c *consoleWriter) WriteMsg(lm *LogMsg) error {
if lm.Level > c.Level {
return nil
}
// fmt.Printf("Formatted: %s\n\n", c.fmtter.Format(lm))
msg := ""
if c.Colorful {
lm.Msg = strings.Replace(lm.Msg, levelPrefix[lm.Level], colors[lm.Level](levelPrefix[lm.Level]), 1)
}
msg := ""
if c.customFormatter != nil {
msg = c.customFormatter(lm)
} else {

View File

@ -0,0 +1,36 @@
package logformattertest
import (
"fmt"
"testing"
"github.com/astaxie/beego/pkg/common"
"github.com/astaxie/beego/pkg/logs"
)
func customFormatter(lm *logs.LogMsg) string {
return fmt.Sprintf("[CUSTOM CONSOLE LOGGING] %s", lm.Msg)
}
func globalFormatter(lm *logs.LogMsg) string {
return fmt.Sprintf("[GLOBAL] %s", lm.Msg)
}
func TestCustomLoggingFormatter(t *testing.T) {
// beego.BConfig.Log.AccessLogs = true
logs.SetLoggerWithOpts("console", []string{`{"color":true}`}, common.SimpleKV{Key: "formatter", Value: customFormatter})
// Message will be formatted by the customFormatter with colorful text set to true
logs.Informational("Test message")
}
func TestGlobalLoggingFormatter(t *testing.T) {
logs.SetGlobalFormatter(globalFormatter)
logs.SetLogger("console", `{"color":true}`)
// Message will be formatted by globalFormatter
logs.Informational("Test message")
}