-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathPickleGraphiteSender.cs
More file actions
111 lines (95 loc) · 3.12 KB
/
PickleGraphiteSender.cs
File metadata and controls
111 lines (95 loc) · 3.12 KB
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
using System;
using System.Net;
using System.Net.Sockets;
using Metrics.Logging;
using Metrics.Utils;
namespace Metrics.Graphite
{
public sealed class PickleGraphiteSender : GraphiteSender
{
private static readonly ILog log = LogProvider.GetCurrentClassLogger();
public const int DefaultPickleJarSize = 100;
private readonly string host;
private readonly int port;
private readonly int pickleJarSize;
private readonly bool _keysToLowercase;
private TcpClient client;
private PickleJar jar = new PickleJar();
public PickleGraphiteSender(string host, int port, int batchSize = DefaultPickleJarSize, bool keysToLowercase = false)
{
this.host = host;
this.port = port;
this.pickleJarSize = batchSize;
_keysToLowercase = keysToLowercase;
}
public override void Send(string name, string value, string timestamp)
{
if (_keysToLowercase)
name = name.ToLower();
this.jar.Append(name, value, timestamp);
if (jar.Size >= this.pickleJarSize)
{
WriteCurrentJar();
this.jar = new PickleJar();
}
}
private void WriteCurrentJar()
{
try
{
if (this.client == null)
{
this.client = InitClient(this.host, this.port);
}
this.jar.WritePickleData(this.client.GetStream());
}
catch (Exception x)
{
using (this.client) { }
this.client = null;
MetricsErrorHandler.Handle(x, "Error sending Pickled data to graphite endpoint " + host + ":" + port.ToString());
}
}
protected override void SendData(string data)
{ }
public override void Flush()
{
try
{
WriteCurrentJar();
if (this.client != null)
{
this.client.GetStream().Flush();
}
}
catch (Exception x)
{
using (this.client) { }
this.client = null;
MetricsErrorHandler.Handle(x, "Error sending Pickled data to graphite endpoint " + host + ":" + port.ToString());
}
}
private static TcpClient InitClient(string host, int port)
{
var endpoint = new IPEndPoint(HostResolver.Resolve(host), port);
var client = new TcpClient();
client.Connect(endpoint);
log.Debug(() => "Picked client for graphite initialized for " + host + ":" + port.ToString());
return client;
}
protected override void Dispose(bool disposing)
{
Flush();
using (this.client)
{
try
{
this.client.Close();
}
catch { }
}
this.client = null;
base.Dispose(disposing);
}
}
}