-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsumo.go
114 lines (92 loc) · 2.44 KB
/
sumo.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package sumogrip
import (
"context"
"fmt"
"log"
"net/url"
"os"
"github.com/deciduosity/grip/message"
"github.com/deciduosity/grip/send"
sumo "github.com/nutmegdevelopment/sumologic/upload"
)
type sumoLogger struct {
endpoint string
client sumoClient
*send.Base
}
const sumoEndpointEnvVar = "GRIP_SUMO_ENDPOINT"
// MakeSumo constructs a Sumo logging backend that reads the private
// URL endpoint from the GRIP_SUMO_ENDPOINT environment variable.
//
// The instance is otherwise unconquered. Call SetName or inject it
// into a Journaler instance using SetSender before using.
//
// The logger uses the JSON formatter by default.
func MakeSumo() (send.Sender, error) {
endpoint := os.Getenv(sumoEndpointEnvVar)
s, err := NewSumo("", endpoint)
if err != nil {
return nil, err
}
return s, nil
}
// NewSumo constructs a Sumo logging backend that sends messages to the
// private URL endpoint of an HTTP source.
//
// The logger uses the JSON formatter by default.
func NewSumo(name, endpoint string) (send.Sender, error) {
s := &sumoLogger{
endpoint: endpoint,
client: &sumoClientImpl{},
}
fallback := log.New(os.Stdout, "", log.LstdFlags)
s.Base = send.MakeBase(
// name
name,
// reset
func() {
fallback.SetPrefix(fmt.Sprintf("[%s] ", s.Name()))
},
// closer
func() error { return nil })
s.client.Create(s.endpoint)
if _, err := url.ParseRequestURI(s.endpoint); err != nil {
return nil, fmt.Errorf("cannot connect to url '%s': %s", s.endpoint, err)
}
if err := s.SetErrorHandler(send.ErrorHandlerFromLogger(fallback)); err != nil {
return nil, err
}
if err := s.SetFormatter(send.MakeJSONFormatter()); err != nil {
return nil, err
}
return s, nil
}
func (s *sumoLogger) Send(m message.Composer) {
if s.Level().ShouldLog(m) {
text, err := s.Formatter()(m)
if err != nil {
s.ErrorHandler()(err, m)
return
}
buf := []byte(text)
if err := s.client.Send(buf, s.Name()); err != nil {
s.ErrorHandler()(err, m)
}
}
}
func (s *sumoLogger) Flush(_ context.Context) error { return nil }
////////////////////////////////////////////////////////////////////////
//
// interface to wrap sumologic client interaction
//
////////////////////////////////////////////////////////////////////////
type sumoClient interface {
Create(string)
Send([]byte, string) error
}
type sumoClientImpl struct {
sumo.Uploader
}
func (c *sumoClientImpl) Create(endpoint string) {
c.Uploader = sumo.NewUploader(endpoint)
}