unix_socket/unix-socket.rs
1// Cadence - An extensible Statsd client for Rust!
2//
3// To the extent possible under law, the author(s) have dedicated all copyright and
4// related and neighboring rights to this file to the public domain worldwide.
5// This software is distributed without any warranty.
6//
7// You should have received a copy of the CC0 Public Domain Dedication along with this
8// software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
9
10// This example shows how you can write metrics to a Unix datagram socket instead
11// of a UDP socket. This might be useful if you have some sort of Statsd server or
12// agent running on the same machine as your application that is exposed via a Unix
13// socket.
14//
15// In this example we make use of some of the Cadence testing code to cut down
16// on the amount of boilerplate we need to write. The server harness here spins
17// up a server, runs the provided closure with the path to the socket as an
18// argument, then waits for the server to shut down.
19
20use cadence::prelude::*;
21use cadence::test::UnixServerHarness;
22use cadence::{StatsdClient, UnixMetricSink};
23use std::os::unix::net::UnixDatagram;
24use std::time::Duration;
25
26fn main() {
27 let harness = UnixServerHarness::new("unix-socket-example");
28 harness.run(
29 |s: String| println!("Got {} bytes from socket: {}", s.len(), s),
30 |path| {
31 let socket = UnixDatagram::unbound().unwrap();
32 let sink = UnixMetricSink::from(path, socket);
33 let client = StatsdClient::from_sink("example.prefix", sink);
34
35 client.count("example.counter", 1).unwrap();
36 client.gauge("example.gauge", 5).unwrap();
37 client.gauge("example.gauge", 5.0).unwrap();
38 client.time("example.timer", 32).unwrap();
39 client.time("example.timer", Duration::from_millis(32)).unwrap();
40 client.histogram("example.histogram", 22).unwrap();
41 client.histogram("example.histogram", Duration::from_nanos(22)).unwrap();
42 client.histogram("example.histogram", 22.0).unwrap();
43 client.distribution("example.distribution", 33).unwrap();
44 client.distribution("example.distribution", 33.0).unwrap();
45 client.meter("example.meter", 8).unwrap();
46 client.set("example.set", 44).unwrap();
47 },
48 );
49}