@@ -36,6 +36,10 @@ local defaults = {
3636 constant_tags = {" source:apisix" }
3737}
3838
39+ -- DogStatsD agent's default receive buffer (dogstatsd_buffer_size); datagrams
40+ -- larger than this are silently truncated, so cap coalescing here
41+ local MAX_DATAGRAM_SIZE = 8192
42+
3943local batch_processor_manager = bp_manager_mod .new (plugin_name )
4044
4145-- Shared schema for individual tag strings.
@@ -142,7 +146,7 @@ local function generate_tag(entry, const_tags)
142146end
143147
144148
145- -- Build all DogStatsD metrics for one entry as a single newline-delimited packet .
149+ -- Build the DogStatsD metric lines for one entry.
146150local function build_metrics (entry , metadata )
147151 -- Generate prefix & suffix according dogstatsd udp data format.
148152 local suffix = generate_tag (entry , metadata .value .constant_tags )
@@ -168,7 +172,7 @@ local function build_metrics(entry, metadata)
168172 core .table .insert (metrics , format (" %s:%s|%s%s" , prefix .. " egress.size" ,
169173 entry .response .size , " ms" , suffix ))
170174
171- return concat ( metrics , " \n " )
175+ return metrics
172176end
173177
174178
@@ -197,8 +201,27 @@ local function push_metrics(entries)
197201
198202 local err_msg , first_fail
199203 for i = 1 , # entries do
200- -- coalesce the per-request metrics into one datagram
201- local send_ok , send_err = sock :send (build_metrics (entries [i ], metadata ))
204+ local lines = build_metrics (entries [i ], metadata )
205+ local payload = concat (lines , " \n " )
206+
207+ local send_ok , send_err
208+ if # payload <= MAX_DATAGRAM_SIZE then
209+ -- coalesce the entry's metrics into one datagram
210+ send_ok , send_err = sock :send (payload )
211+ else
212+ -- too large to coalesce safely: one datagram per metric
213+ for j = 1 , # lines do
214+ if # lines [j ] > MAX_DATAGRAM_SIZE then
215+ core .log .warn (" dogstatsd metric line exceeds " , MAX_DATAGRAM_SIZE ,
216+ " bytes, agent may truncate it" )
217+ end
218+ send_ok , send_err = sock :send (lines [j ])
219+ if not send_ok then
220+ break
221+ end
222+ end
223+ end
224+
202225 if not send_ok then
203226 err_msg = " failed to send metrics to dogstatsd server: host[" .. host
204227 .. " ] port[" .. tostring (port ) .. " ] err: " .. send_err
0 commit comments