Skip to content

Commit

Permalink
improved custom formatter example; closes #9
Browse files Browse the repository at this point in the history
  • Loading branch information
steenzout committed Nov 18, 2015
1 parent 557e2f1 commit 23bf1b7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
8 changes: 7 additions & 1 deletion internal/examples/formatters/custom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ This example demonstrates a case where
you have a logger that writes to `stdout` using a custom message formatter.

```
# install dependencies
$ go get github.com/fatih/color
# build
$ go buid example.go
$ go run example.go
# run
$ ./custom
severity:EMERGENCY message:system is down
severity:ALERT message:failed to write to disk
severity:CRITICAL message:high server load
Expand Down
21 changes: 18 additions & 3 deletions internal/examples/formatters/custom/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import (
"strings"

"github.com/mediaFORGE/gol"
"github.com/mediaFORGE/gol/fields"
field_severity "github.com/mediaFORGE/gol/fields/severity"
"github.com/mediaFORGE/gol/loggers/simple"

"github.com/fatih/color"
)

// Custom struct for a custom formatter.
Expand All @@ -19,11 +23,22 @@ func (f Custom) Format(msg *gol.LogMessage) (string, error) {

i := 0
for k, v := range *msg {
buffer[i] = fmt.Sprintf("%s:'%s'", k, v)
i += 1
if k != fields.Severity {
buffer[i] = fmt.Sprintf("%s:'%s'", k, v)
i += 1
}
}

return fmt.Sprintf("%s\n", strings.Join(buffer, " ")), nil
if severity, err := msg.Severity(); err != nil {
return fmt.Sprintf("UNKNOWN %s\n", strings.Join(buffer, " ")), nil
} else {
switch severity >= field_severity.Error {
case true:
return fmt.Sprintf("%s %s\n", color.RedString("%s", severity), strings.Join(buffer, " ")), nil
default:
return fmt.Sprintf("%s %s\n", severity, strings.Join(buffer, " ")), nil
}
}
}

var _ gol.LogFormatter = (*Custom)(nil)
Expand Down

0 comments on commit 23bf1b7

Please sign in to comment.