1 module syslog.serviceclient;
2 
3 import vibe.core.core:runTask;
4 import vibe.core.log:logError;
5 import vibe.http.client;
6 
7 ///
8 class SyslogServiceClient
9 {
10 private:
11 	immutable string m_url;
12 	bool m_logSendErrors = false;
13 
14 public:
15 
16 	///
17 	@property void logSendErrors(bool _val) { m_logSendErrors = _val; }
18 
19 	///
20 	this(in string _url)
21 	{
22 		import std.string:endsWith;
23 
24 		if(_url.length > 0 && !_url.endsWith("/"))
25 			m_url = _url~"/";
26 		else
27 			m_url = _url;
28 	}
29 
30 	///
31 	void log(string _event)(in string[string] _params)
32 	{
33 		if(m_url.length == 0)
34 			return;
35 
36 		runTask({
37 			auto requestUrl = m_url~getAdditionalUrlString()~_event;
38 
39 			try 
40 			{
41 				auto res = requestHTTP(requestUrl,
42 				(scope HTTPClientRequest req) {
43 					prepareRequest(req);
44 		
45 					import vibe.http.form;
46 					req.writeFormBody(_params);
47 				});
48 				scope(exit) res.dropBody();
49 			}
50 			catch(Exception e)
51 			{
52 				if(m_logSendErrors)
53 					logError("syslog send error");
54 			}
55 		});
56 	}
57 
58 	///
59 	void log(string _event, T...)(in T _params)
60 	{
61 		static assert(T.length % 2 == 0, "odd number of parameters requiered");
62 
63 		import std.conv:to;
64 
65 		if(m_url.length == 0)
66 			return;
67 
68 		string[T.length] paramArray;
69 
70 		foreach(i,param; _params)
71 		{
72 			paramArray[i] = to!string(param);
73 		}
74 
75 		string[string] paramAA;
76 
77 		foreach(i; 0..paramArray.length/2)
78 		{
79 			paramAA[paramArray[i*2]] = paramArray[i*2+1];
80 		}
81 
82 		log!(_event)(paramAA);
83 	}
84 
85 	///
86 	void log(string _event)()
87 	{
88 		if(m_url.length == 0)
89 			return;
90 
91 		runTask({
92 			auto requestUrl = m_url~getAdditionalUrlString()~_event;
93 
94 			try 
95 			{
96 				auto res = requestHTTP(requestUrl,
97 				(scope HTTPClientRequest req) {
98 					prepareRequest(req);
99 
100 					req.writeBody(cast(ubyte[])"");
101 				});
102 				scope(exit) res.dropBody();
103 			}
104 			catch(Exception e)
105 			{
106 				if(m_logSendErrors)
107 					logError("syslog send error");
108 			}
109 		});
110 	}
111 
112 	///
113 	protected string getAdditionalUrlString()
114 	{
115 		return "";
116 	}
117 
118 	///
119 	private static void prepareRequest(scope HTTPClientRequest req)
120 	{
121 		req.method = HTTPMethod.POST;
122 	}
123 }
124 
125 version(none)
126 {
127 	shared static this()
128 	{
129 		SyslogServiceClient logger = new SyslogServiceClient("http://localhost:8888/");
130 
131 		logger.log!"event1"();
132 
133 		logger.log!"event2"("param2","value");
134 	}
135 }