Skip to content
This repository has been archived by the owner on Mar 18, 2019. It is now read-only.

Commit

Permalink
Merge pull request #29 from scorptec68/master
Browse files Browse the repository at this point in the history
For RFC5424 APP-NAME is limited to 48 chars - so truncate it
  • Loading branch information
sirsean authored Jan 18, 2018
2 parents 4d2c753 + c940732 commit f6152a1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 11 additions & 1 deletion formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"time"
)

const appNameMaxLength = 48 // limit to 48 chars as per RFC5424

// Formatter is a type of function that takes the consituent parts of a
// syslog message and returns a formatted string. A different Formatter is
// defined for each different syslog protocol we support.
Expand Down Expand Up @@ -37,11 +39,19 @@ func RFC3164Formatter(p Priority, hostname, tag, content string) string {
return msg
}

// if string's length is greater than max, then use the last part
func truncateStartStr(s string, max int) string {
if (len(s) > max) {
return s[len(s) - max:]
}
return s
}

// RFC5424Formatter provides an RFC 5424 compliant message.
func RFC5424Formatter(p Priority, hostname, tag, content string) string {
timestamp := time.Now().Format(time.RFC3339)
pid := os.Getpid()
appName := os.Args[0]
appName := truncateStartStr(os.Args[0], appNameMaxLength)
msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s",
p, 1, timestamp, hostname, appName, pid, tag, content)
return msg
Expand Down
15 changes: 14 additions & 1 deletion formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"testing"
"time"
"strings"
)

func TestDefaultFormatter(t *testing.T) {
Expand Down Expand Up @@ -37,8 +38,20 @@ func TestRFC3164Formatter(t *testing.T) {
func TestRFC5424Formatter(t *testing.T) {
out := RFC5424Formatter(LOG_ERR, "hostname", "tag", "content")
expected := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s",
LOG_ERR, 1, time.Now().Format(time.RFC3339), "hostname", os.Args[0], os.Getpid(), "tag", "content")
LOG_ERR, 1, time.Now().Format(time.RFC3339), "hostname", truncateStartStr(os.Args[0], appNameMaxLength),
os.Getpid(), "tag", "content")
if out != expected {
t.Errorf("expected %v got %v", expected, out)
}
}

func TestTruncateStartStr(t *testing.T) {
out := truncateStartStr("abcde", 3)
if strings.Compare(out, "cde" ) != 0 {
t.Errorf("expected \"cde\" got %v", out)
}
out = truncateStartStr("abcde", 5)
if strings.Compare(out, "abcde" ) != 0 {
t.Errorf("expected \"abcde\" got %v", out)
}
}

0 comments on commit f6152a1

Please sign in to comment.