@@ -14,9 +14,17 @@ import (
1414)
1515
1616const (
17+
18+ // DefaultHost is the default host to which the datadog client tries to
19+ DefaultHost = "localhost"
20+
21+ // DefaultPort is the default port to which the datadog client tries to
22+ // connect to.
23+ DefaultPort = "8125"
24+
1725 // DefaultAddress is the default address to which the datadog client tries
1826 // to connect to.
19- DefaultAddress = "localhost:8125"
27+ DefaultAddress = DefaultHost + ":" + DefaultPort
2028
2129 // DefaultBufferSize is the default size for batches of metrics sent to
2230 // datadog.
@@ -77,11 +85,19 @@ func NewClient(addr string) *Client {
7785 })
7886}
7987
88+ // NewClientFromEnv creates and returns a new datadog client publishing metrics
89+ // to the server running at the address specified in the environment variable.
90+ // The STATSD_HOST and STATSD_UDP_PORT environment variables are used to
91+ // determine the address.
92+ func NewClientFromEnv () * Client {
93+ return NewClientWith (ClientConfig {})
94+ }
95+
8096// NewClientWith creates and returns a new datadog client configured with the
8197// given config.
8298func NewClientWith (config ClientConfig ) * Client {
8399 if len (config .Address ) == 0 {
84- config .Address = DefaultAddress
100+ config .Address = addressFromEnv ()
85101 }
86102
87103 if config .BufferSize == 0 {
@@ -153,6 +169,25 @@ func (c *Client) Close() error {
153169 return c .err
154170}
155171
172+ // Returns the address to which the client will send metrics by
173+ // looking at the STATSD_SOCKET, STATSD_HOST and STATSD_UDP_PORT environment variables.
174+ func addressFromEnv () string {
175+ socket := os .Getenv ("STATSD_SOCKET" )
176+ if len (socket ) > 0 {
177+ return "unixgram://" + socket
178+ }
179+ hostname := os .Getenv ("STATSD_HOST" )
180+ if len (hostname ) == 0 {
181+ hostname = DefaultHost
182+ }
183+ port := os .Getenv ("STATSD_UDP_PORT" )
184+ if len (port ) == 0 {
185+ port = DefaultPort
186+ }
187+ addr := hostname + ":" + port
188+ return addr
189+ }
190+
156191func bufSizeFromFD (f * os.File , sizehint int ) (bufsize int , err error ) {
157192 fd := int (f .Fd ())
158193
0 commit comments