File: apexlogs.go

package info (click to toggle)
golang-github-apex-log 1.1.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports, bullseye, experimental, forky, sid, trixie
  • size: 316 kB
  • sloc: makefile: 4
file content (78 lines) | stat: -rw-r--r-- 1,487 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Package apexlogs implements a handler for Apex Logs.
package apexlogs

import (
	"sync"

	"github.com/apex/log"
	"github.com/apex/log/handlers/apexlogs/client"
)

// TODO: periodic buffering

var levelMap = map[log.Level]string{
	log.DebugLevel: "debug",
	log.InfoLevel:  "info",
	log.WarnLevel:  "warning",
	log.ErrorLevel: "error",
	log.FatalLevel: "emergency",
}

// Handler implementation.
type Handler struct {
	// URL is the endpoint for your Apex Logs deployment API.
	URL string

	// ProjectID is the id of the project that you are collecting logs for.
	ProjectID string

	// buffer
	mu     sync.Mutex
	buffer []client.Event

	// client
	once sync.Once
	c    client.Client
}

// HandleLog implements log.Handler.
func (h *Handler) HandleLog(e *log.Entry) error {
	// initialize client
	h.once.Do(func() {
		h.c = client.Client{
			URL: h.URL,
		}
	})

	// create event
	event := client.Event{
		Level:     levelMap[e.Level],
		Message:   e.Message,
		Fields:    map[string]interface{}(e.Fields),
		Timestamp: e.Timestamp,
	}

	// buffer event
	h.mu.Lock()
	h.buffer = append(h.buffer, event)
	h.mu.Unlock()

	return nil
}

// Events returns the buffered events, and clears the buffer.
func (h *Handler) Events() (events []client.Event) {
	h.mu.Lock()
	events = h.buffer
	h.buffer = nil
	h.mu.Unlock()
	return
}

// Flush all buffered logs.
func (h *Handler) Flush() error {
	return h.c.AddEvents(client.AddEventsInput{
		ProjectID: h.ProjectID,
		Events:    h.Events(),
	})
}