Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ColorHeaderAndFields logger option #118

Merged
merged 7 commits into from Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
109 changes: 84 additions & 25 deletions intlogger.go
Expand Up @@ -70,6 +70,7 @@ type intLogger struct {
level *int32

headerColor ColorOption
fieldColor ColorOption

implied []interface{}

Expand Down Expand Up @@ -115,14 +116,19 @@ func newLogger(opts *LoggerOptions) *intLogger {
mutex = new(sync.Mutex)
}

var primaryColor, headerColor ColorOption

if opts.ColorHeaderOnly {
primaryColor = ColorOff
var (
primaryColor ColorOption = ColorOff
headerColor ColorOption = ColorOff
fieldColor ColorOption = ColorOff
)
switch {
case opts.ColorHeaderOnly:
headerColor = opts.Color
} else {
case opts.ColorHeaderAndFields:
fieldColor = opts.Color
headerColor = opts.Color
default:
primaryColor = opts.Color
headerColor = ColorOff
}

l := &intLogger{
Expand All @@ -137,6 +143,7 @@ func newLogger(opts *LoggerOptions) *intLogger {
exclude: opts.Exclude,
independentLevels: opts.IndependentLevels,
headerColor: headerColor,
fieldColor: fieldColor,
}
if opts.IncludeLocation {
l.callerOffset = offsetIntLogger + opts.AdditionalLocationOffset
Expand Down Expand Up @@ -235,7 +242,18 @@ func needsQuoting(str string) bool {
return false
}

// Non-JSON logging format function
// logPlain is the non-JSON logging format function which writes directly
// to the underlying writer the logger was initialized with.
//
// If the logger was initialized with a color function, it also handles
// applying the color to the log message.
//
// Color Options
// 1. No color.
// 2. Color the whole log line, based on the level.
// 3. Color only the header (level) part of the log line.
// 4. Color both the header and fields of the log line.
//
func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, args ...interface{}) {

if !l.disableTime {
Expand All @@ -245,10 +263,11 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string,

s, ok := _levelToBracket[level]
if ok {
if l.headerColor != ColorOff {
switch {
case l.headerColor != ColorOff:
color := _levelToColor[level]
color.Fprint(l.writer, s)
} else {
default:
picatz marked this conversation as resolved.
Show resolved Hide resolved
l.writer.WriteString(s)
}
} else {
Expand Down Expand Up @@ -281,7 +300,7 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string,

var stacktrace CapturedStacktrace

if args != nil && len(args) > 0 {
if len(args) > 0 {
if len(args)%2 != 0 {
cs, ok := args[len(args)-1].(CapturedStacktrace)
if ok {
Expand All @@ -295,13 +314,16 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string,

l.writer.WriteByte(':')

// Handle the field arguments, which come in pairs (key=val).
FOR:
for i := 0; i < len(args); i = i + 2 {
var (
key string
val string
raw bool
)

// Convert the field value to a string.
switch st := args[i+1].(type) {
case string:
val = st
Expand Down Expand Up @@ -353,32 +375,69 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string,
}
}

var key string

// Convert the field key to a string.
switch st := args[i].(type) {
case string:
key = st
default:
key = fmt.Sprintf("%s", st)
}

if strings.Contains(val, "\n") {
l.writer.WriteString("\n ")
l.writer.WriteString(key)
l.writer.WriteString("=\n")
writeIndent(l.writer, val, " | ")
l.writer.WriteString(" ")
} else if !raw && needsQuoting(val) {
// Optionally apply the ANSI "dim" (faint) and "bold"
// SGR values to the key.
if l.fieldColor != ColorOff {
color := color.New(color.Faint, color.Bold)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems weird to use faint and bold. Why not just bold?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like faint helps break up a log line visually, for me, better than just bold.

Just Bold

Screen Shot 2022-08-29 at 1 31 52 PM

Bold and Faint

Screen Shot 2022-08-29 at 1 32 25 PM

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The concern is mostly how other folks default terminal fonts will handle faint+bold. We have to be careful picking here because it has a big influence on all the users.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a fair point. I think the Windows terminal would likely be the odd one to consider, and it seems like they do support this style: microsoft/terminal#6703 (comment)

Faint/dim is a fairly standard SGR style, implemented in VSCode's terminal emulator (xtermjs) as well (which is what those screenshots are showing).

Bold, I believe, is the more widely supported style. But, I would really rather have faint than bold here to help break up the line. I feel it's important. I don't know if we can actually detect if it's supported?

key = color.Sprint(key)
}

// Values may contain multiple lines, and that format
// is preserved, with each line prefixed with a " | "
// to show it's part of a collection of lines.
//
// Values may also neeq quoting, if not all the runes
// in the value string are "normal", like if they
// contain ANSI escape sequences.
switch {
case strings.Contains(val, "\n"):
picatz marked this conversation as resolved.
Show resolved Hide resolved
key = "\n " + key

valStrBuilder := &strings.Builder{}
valStrWriter := newWriter(valStrBuilder, ColorOff)

valStrBuilder.WriteString("\n")

if l.fieldColor != ColorOff {
color := color.New(color.Faint)
writeIndent(valStrWriter, val, color.Sprint(" | "))
} else {
writeIndent(valStrWriter, val, " | ")
}
valStrWriter.Flush(level)
picatz marked this conversation as resolved.
Show resolved Hide resolved

valStrBuilder.WriteString(" ")

val = valStrBuilder.String()
case !raw && needsQuoting(val):
val = strconv.Quote(val)
}

// If the key contains a newline, because the value itself
// contains newlines, then we pad with an extra space.
if !strings.Contains(key, "\n") {
picatz marked this conversation as resolved.
Show resolved Hide resolved
l.writer.WriteByte(' ')
l.writer.WriteString(key)
l.writer.WriteByte('=')
l.writer.WriteString(strconv.Quote(val))
}
l.writer.WriteString(key)

if l.fieldColor != ColorOff {
faintColor := color.New(color.Faint)
faintColor.Fprint(l.writer, "=")
resetColor := color.New(color.Reset)
resetColor.Fprint(l.writer, "")
picatz marked this conversation as resolved.
Show resolved Hide resolved
} else {
l.writer.WriteByte(' ')
l.writer.WriteString(key)
l.writer.WriteByte('=')
l.writer.WriteString(val)
}

l.writer.WriteString(val)
}
}

Expand Down
4 changes: 4 additions & 0 deletions logger.go
Expand Up @@ -274,6 +274,10 @@ type LoggerOptions struct {
// Only color the header, not the body. This can help with readability of long messages.
ColorHeaderOnly bool

// Color the header and message body fields. This can help with readability
// of long messages with multiple fields.
ColorHeaderAndFields bool

// A function which is called with the log information and if it returns true the value
// should not be logged.
// This is useful when interacting with a system that you wish to suppress the log
Expand Down