Hello everyone,
I'm looking to create a logger handler that sends logs to a remote endpoint using HTTP. I need the logger handler to have the following functionalities:
- It should run in the background so that it does not affect the execution of the main program from the network request.
- It should continue sending logs even if the execution of the main program is complete.
I wrote the following code:
type HttpLogHandler struct {
endpoint string
requestQueue chan []byte
httpClient *http.Client
waitGroup sync.WaitGroup
}
func NewHttpLogHandler(endpoint string) *HttpLogHandler {
requestQueue := make(chan []byte, 1000)
httpClient := &http.Client{}
h := &HttpLogHandler{
endpoint: endpoint,
requestQueue: requestQueue,
httpClient: httpClient,
}
h.waitGroup.Add(1)
go h.writeToEndpoint()
return h
}
func (h *HttpLogHandler) writeToEndpoint() {
defer h.waitGroup.Done()
for data := range h.requestQueue {
_, err := h.httpClient.Post(h.endpoint, "text/plain", bytes.NewReader(data))
if err != nil {
log.Printf("Error sending log data to endpoint: %v", err)
}
}
h.waitGroup.Wait()
}
func (h *HttpLogHandler) Write(data []byte) (int, error) {
h.requestQueue <- data
return len(data), nil
}
This code currently fulfill the first requirement, but would not the second one. Anyone has any idea how do handle this?