Skip to content

Commit

Permalink
Merge pull request #31 from mlycore/dev
Browse files Browse the repository at this point in the history
refactor: refactor color render of LogEntry
  • Loading branch information
mlycore authored Mar 13, 2024
2 parents 9a808e2 + 0198a9a commit bcc9239
Showing 1 changed file with 45 additions and 41 deletions.
86 changes: 45 additions & 41 deletions entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,48 +55,52 @@ func (e *LogEntry) SetLevel(lv string) *LogEntry {

func (e *LogEntry) Render() *LogEntry {
if e.color {
switch e.level {
case EnvLogLevelError:
e.buf = append(e.buf, "\033[31m"...)
e.buf = append(e.buf, e.timestamp...)
e.buf = append(e.buf, " ["...)
e.buf = append(e.buf, e.level...)
e.buf = append(e.buf, "] "...)
e.buf = append(e.buf, e.msg...)
e.buf = append(e.buf, "\033[0m"...)
if e.newline {
e.buf = append(e.buf, '\n')
}
case EnvLogLevelDebug:
e.buf = append(e.buf, "\033[1;34m"...)
e.buf = append(e.buf, e.timestamp...)
e.buf = append(e.buf, " ["...)
e.buf = append(e.buf, e.level...)
e.buf = append(e.buf, "] "...)
e.buf = append(e.buf, e.msg...)
e.buf = append(e.buf, "\033[0m"...)
if e.newline {
e.buf = append(e.buf, '\n')
}
default:
e.buf = append(e.buf, e.timestamp...)
e.buf = append(e.buf, " ["...)
e.buf = append(e.buf, e.level...)
e.buf = append(e.buf, "] "...)
e.buf = append(e.buf, e.msg...)
if e.newline {
e.buf = append(e.buf, '\n')
}
}
e.colorize()
} else {
e.buf = append(e.buf, e.timestamp...)
e.buf = append(e.buf, " ["...)
e.buf = append(e.buf, e.level...)
e.buf = append(e.buf, "] "...)
e.buf = append(e.buf, e.msg...)
if e.newline {
e.buf = append(e.buf, '\n')
}
e.render()
}
if e.newline {
e.buf = append(e.buf, '\n')
}
return e
}

func (e *LogEntry) render() *LogEntry {
e.buf = append(e.buf, e.timestamp...)
e.buf = append(e.buf, " ["...)
e.buf = append(e.buf, e.level...)
e.buf = append(e.buf, "] "...)
e.buf = append(e.buf, e.msg...)
return e
}

type palette []string

func (p palette) pair() (string, string) {
return p[0], p[1]
}

var (
blue palette = []string{"\033[31m", "\033[0m"}
red palette = []string{"\033[1;34m", "\033[0m"}
)

func (e *LogEntry) renderc(color palette) *LogEntry {
prefix, suffix := color.pair()
e.buf = append(e.buf, prefix...)
e.render()
e.buf = append(e.buf, suffix...)
return e
}

func (e *LogEntry) colorize() *LogEntry {
switch e.level {
case EnvLogLevelError:
e.renderc(blue)
case EnvLogLevelDebug:
e.renderc(red)
default:
e.render()
}
return e
}
Expand Down

0 comments on commit bcc9239

Please sign in to comment.