Skip to content

Commit

Permalink
Merge pull request #2 from kiall/discardafterclose
Browse files Browse the repository at this point in the history
Implement io.WriteCloser to allow flushing logs
  • Loading branch information
gllm-dev authored Nov 30, 2023
2 parents e30e8b5 + 71b943b commit a767a46
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
14 changes: 11 additions & 3 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import "github.com/fluent/fluent-logger-golang/fluent"

// Config is used to configure the Writer.
type Config struct {
fluentConfig *fluent.Config
basicConfig *BasicConfig
tag string
fluentConfig *fluent.Config
basicConfig *BasicConfig
tag string
discardWritesAfterClose bool
}

// BasicConfig is used to configure the Writer with a basic configuration.
Expand Down Expand Up @@ -40,3 +41,10 @@ func WithTag(tag string) func(*Config) {
c.tag = tag
}
}

// WithDiscardWritesAfterClose returns a function that can be used to configure the Writer to discard writes after Close()
func WithDiscardWritesAfterClose() func(*Config) {
return func(c *Config) {
c.discardWritesAfterClose = true
}
}
30 changes: 24 additions & 6 deletions fluent.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ package fluentio

import (
"encoding/json"
"github.com/fluent/fluent-logger-golang/fluent"
"io"

"github.com/fluent/fluent-logger-golang/fluent"
)

// Writer is an io.Writer that writes to fluentd.
type Writer struct {
client *fluent.Fluent
tag string
config *Config
client *fluent.Fluent
tag string
discardWrites bool
}

var _ io.Writer = (*Writer)(nil)
var _ io.WriteCloser = (*Writer)(nil)

// New creates a new Writer.
// It accepts a variadic number of options that can be used to configure the Writer.
Expand Down Expand Up @@ -47,13 +50,20 @@ func New(opts ...func(config *Config)) (*Writer, error) {
}

return &Writer{
client: client,
tag: tag,
config: config,
client: client,
tag: tag,
discardWrites: false,
}, nil
}

// Write is the implementation of io.Writer.
func (f *Writer) Write(p []byte) (n int, err error) {
// If the Writer has been closed,
if f.discardWrites {
return len(p), nil
}

var m map[string]interface{}
err = json.Unmarshal(p, &m)
if err != nil {
Expand All @@ -67,3 +77,11 @@ func (f *Writer) Write(p []byte) (n int, err error) {

return len(p), nil
}

// Close is the implementation of io.Closer.
func (f *Writer) Close() error {
if f.config.discardWritesAfterClose {
f.discardWrites = true
}
return f.client.Close()
}

0 comments on commit a767a46

Please sign in to comment.