Handle binary in log, close #733

This commit is contained in:
Jinzhu 2016-03-04 09:12:01 +08:00
parent 8b291cc32b
commit e0cca89ce3
1 changed files with 15 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import (
"reflect" "reflect"
"regexp" "regexp"
"time" "time"
"unicode"
) )
type logger interface { type logger interface {
@ -48,7 +49,11 @@ func (logger Logger) Print(values ...interface{}) {
if t, ok := value.(time.Time); ok { if t, ok := value.(time.Time); ok {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format(time.RFC3339))) formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format(time.RFC3339)))
} else if b, ok := value.([]byte); ok { } else if b, ok := value.([]byte); ok {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", string(b))) if str := string(b); isPrintable(str) {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
} else {
formattedValues = append(formattedValues, "'<binary>'")
}
} else if r, ok := value.(driver.Valuer); ok { } else if r, ok := value.(driver.Valuer); ok {
if value, err := r.Value(); err == nil && value != nil { if value, err := r.Value(); err == nil && value != nil {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
@ -80,3 +85,12 @@ func (logger Logger) Print(values ...interface{}) {
logger.Println(messages...) logger.Println(messages...)
} }
} }
func isPrintable(s string) bool {
for _, r := range s {
if !unicode.IsPrint(r) {
return false
}
}
return true
}