Refactored RELPHandler to use environment variables for configuration and improved error handling.
This commit is contained in:
parent
473430de19
commit
8cb8013452
@ -14,10 +14,10 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
cacheDir = "/var/cache/relploggercache"
|
||||
diskBufferLimit = 100 // Write to disk after accumulating 100 failed events
|
||||
diskWriteInterval = time.Second // Or write every second, whichever comes first
|
||||
var (
|
||||
cacheDir = os.Getenv("LOGGER_CACHE_DIR")
|
||||
diskBufferLimit = getEnvAsInt("LOGGER_DISK_BUFFER_LIMIT", 100)
|
||||
diskWriteInterval = getEnvAsDuration("LOGGER_DISK_WRITE_INTERVAL", time.Second)
|
||||
)
|
||||
|
||||
type RELPHandler struct {
|
||||
@ -51,7 +51,7 @@ func NewRELPHandler(relpURL string) (*RELPHandler, error) {
|
||||
|
||||
func (r *RELPHandler) Startup() error {
|
||||
var err error
|
||||
r.conn, err = net.Dial("tcp", r.relpServerURL)
|
||||
r.conn, err = r.connectToRELPServer()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to establish TCP connection: %v", err)
|
||||
}
|
||||
@ -104,8 +104,11 @@ func (r *RELPHandler) processFailedEvents() {
|
||||
}
|
||||
|
||||
func (r *RELPHandler) sendEventToRELPServer(event Event) error {
|
||||
jsonData, _ := json.Marshal(event)
|
||||
_, err := r.conn.Write(jsonData)
|
||||
jsonData, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error marshaling event: %v", err)
|
||||
}
|
||||
_, err = r.conn.Write(jsonData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -159,11 +162,16 @@ func (r *RELPHandler) isConnected() bool {
|
||||
|
||||
func (r *RELPHandler) Shutdown() error {
|
||||
close(r.done)
|
||||
return r.conn.Close()
|
||||
if r.conn != nil {
|
||||
if err := r.conn.Close(); err != nil {
|
||||
return fmt.Errorf("error closing TCP connection: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RELPHandler) writeFailedToDisk(event Event) {
|
||||
fileName := filepath.Join(cacheDir, uuid.New().String()+".logevent")
|
||||
data, _ := json.Marshal(event)
|
||||
ioutil.WriteFile(fileName, data, 0644)
|
||||
ioutil.WriteFile(fileName, data, 0600)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user