diff --git a/conn.go b/conn.go index 4ab8b2c..e94ff5a 100644 --- a/conn.go +++ b/conn.go @@ -2,6 +2,7 @@ package journal import ( "net" + "slices" "sync" ) @@ -23,6 +24,7 @@ type Conn struct { s *net.UnixConn bufs sync.Pool + atts sync.Pool } // Connect to the systemd journal. If the path string is empty, then it uses the @@ -40,23 +42,26 @@ func Connect(path string) (*Conn, error) { return nil, err } - return &Conn{ + c := &Conn{ s: s, bufs: sync.Pool{ New: func() any { return &net.Buffers{} }, }, - }, nil + } + c.atts = sync.Pool{ + New: func() any { + return make([]Attr, 0, 2+len(c.Common)) + }, + } + return c, nil } var messageAttrKey = AttrKey{key: "MESSAGE"} // Entry emits a log entry. It will add PRIORITY and MESSAGE key/value pairs // as well as any Common attributes. -// -// Note: to avoid allocation / garbage, ensure attrs has capacity for an extra -// 2+len(c.Common) values. func (c *Conn) Entry(pri Priority, msg string, attrs []Attr) { err := c.EntryErr(pri, msg, attrs) switch { @@ -72,12 +77,18 @@ func (c *Conn) Entry(pri Priority, msg string, attrs []Attr) { // EntryErr is like Entry, but will propagate errors to the caller, rather than // using the built-in error handler. func (c *Conn) EntryErr(pri Priority, msg string, attrs []Attr) error { - attrs = append(attrs, pri.Attr(), Attr{ + a := c.atts.Get().([]Attr) + a = slices.Grow(a[:0], 2+len(c.Common)+len(attrs)) + a = append(a, pri.Attr(), Attr{ Key: messageAttrKey, Value: []byte(msg), }) - attrs = append(attrs, c.Common...) - return c.WriteAttrs(attrs) + a = append(a, c.Common...) + a = append(a, attrs...) + err := c.WriteAttrs(attrs) + slices.Delete(a, 0, len(a)) // ensure GC doesn't see refs to old data + c.atts.Put(a) + return err } // WriteAttrs is a low-level method which writes a journal entry comprised of @@ -86,6 +97,7 @@ func (c *Conn) WriteAttrs(attrs []Attr) error { buf := c.bufs.Get().(*net.Buffers) *buf = (*buf)[:0] err := WireWrite(buf, c.s, attrs) + slices.Delete(*buf, 0, len(*buf)) // ensure GC doesn't see refs to old data c.bufs.Put(buf) return err }