Skip to content

Commit

Permalink
fix: improve multi-line strings
Browse files Browse the repository at this point in the history
  • Loading branch information
caarlos0 committed Jan 16, 2025
1 parent d3a5183 commit e87656e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions _examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,17 @@ func main() {
log.IncreasePadding()
log.WithField("foo", "bar").Info("info with increased padding")
log.IncreasePadding()
log.WithField("foo", "bar").
WithField("text", "a multi\nline text going\non for multiple lines\nhello\nworld!").
Info("info with a more increased padding")
log.WithoutPadding().WithField("foo", "bar").Info("info without padding")
log.WithField("foo", "bar").Info("info with a more increased padding")
log.ResetPadding()
log.WithField("foo", "bar").
WithField("text", "a multi\nline text going\non for multiple lines\nhello\nworld!").
WithField("another", "bar").
WithField("lalalal", "bar").
Info("info with a more increased padding")
log.WithError(errors.New("some error")).Error("error")
log.WithError(errors.New("some fatal error")).Fatal("fatal")
}
18 changes: 18 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package log
import (
"fmt"
"io"
"strings"
"sync"

"github.com/charmbracelet/lipgloss"
Expand Down Expand Up @@ -54,6 +55,8 @@ func (l *Logger) DecreasePadding() {
l.Padding -= defaultPadding
}

const indentSeparator = " │ "

func (l *Logger) handleLog(e *Entry) {
style := Styles[e.Level]
level := Strings[e.Level]
Expand All @@ -69,8 +72,23 @@ func (l *Logger) handleLog(e *Entry) {
e.Message,
)

var previousMultiline bool
for it := e.Fields.Front(); it != nil; it = it.Next() {
if s, ok := it.Value.(string); ok && strings.Contains(s, "\n") {
fmt.Fprintln(l.Writer)
fmt.Fprint(l.Writer, strings.Repeat(" ", e.Padding+2))
fmt.Fprintln(l.Writer, style.Render(it.Key)+"=")
for _, line := range strings.Split(s, "\n") {
fmt.Fprintln(l.Writer, lipgloss.NewStyle().PaddingLeft(e.Padding).Render(indentSeparator+line))
}
previousMultiline = true
continue
}
if previousMultiline {
fmt.Fprint(l.Writer, strings.Repeat(" ", e.Padding+1))
}
fmt.Fprintf(l.Writer, " %s=%v", style.Render(it.Key), it.Value)
previousMultiline = false
}

fmt.Fprintln(l.Writer)
Expand Down

0 comments on commit e87656e

Please sign in to comment.