@@ -14,9 +14,18 @@ import (
1414)
1515
1616const (
17+
18+ // DefaultHost is the default host to which the datadog client tries to
19+ // connect to.
20+ DefaultHost = "localhost"
21+
22+ // DefaultPort is the default port to which the datadog client tries to
23+ // connect to.
24+ DefaultPort = "8125"
25+
1726 // DefaultAddress is the default address to which the datadog client tries
1827 // to connect to.
19- DefaultAddress = "localhost:8125"
28+ DefaultAddress = DefaultHost + ":" + DefaultPort
2029
2130 // DefaultBufferSize is the default size for batches of metrics sent to
2231 // datadog.
@@ -77,11 +86,19 @@ func NewClient(addr string) *Client {
7786 })
7887}
7988
89+ // NewClientFromEnv creates and returns a new datadog client publishing metrics
90+ // to the server running at the address specified in the environment variable.
91+ // The STATSD_HOST and STATSD_UDP_PORT environment variables are used to
92+ // determine the address.
93+ func NewClientFromEnv () * Client {
94+ return NewClientWith (ClientConfig {})
95+ }
96+
8097// NewClientWith creates and returns a new datadog client configured with the
8198// given config.
8299func NewClientWith (config ClientConfig ) * Client {
83100 if len (config .Address ) == 0 {
84- config .Address = DefaultAddress
101+ config .Address = addressFromEnv ()
85102 }
86103
87104 if config .BufferSize == 0 {
@@ -153,6 +170,25 @@ func (c *Client) Close() error {
153170 return c .err
154171}
155172
173+ // Returns the address to which the client will send metrics by
174+ // looking at the STATSD_SOCKET, STATSD_HOST and STATSD_UDP_PORT environment variables.
175+ func addressFromEnv () string {
176+ socket := os .Getenv ("STATSD_SOCKET" )
177+ if len (socket ) > 0 {
178+ return "unixgram://" + socket
179+ }
180+ hostname := os .Getenv ("STATSD_HOST" )
181+ if len (hostname ) == 0 {
182+ hostname = DefaultHost
183+ }
184+ port := os .Getenv ("STATSD_UDP_PORT" )
185+ if len (port ) == 0 {
186+ port = DefaultPort
187+ }
188+ addr := hostname + ":" + port
189+ return addr
190+ }
191+
156192func bufSizeFromFD (f * os.File , sizehint int ) (bufsize int , err error ) {
157193 fd := int (f .Fd ())
158194
0 commit comments