Skip to content

Commit 6d4372c

Browse files
committed
More cleanups.
Add logging to event log. Service-ize-ify.
1 parent 970292b commit 6d4372c

File tree

10 files changed

+143
-25
lines changed

10 files changed

+143
-25
lines changed

src/SyslogProxy/App.config

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?xml version="1.0" encoding="utf-8" ?>
22
<configuration>
33
<appSettings>
4-
<add key="SeqServer" value="http://10.2.10.156:5341"/>
4+
<add key="SeqServer" value="http://localhost:5341"/>
55
<add key="MessageTemplate" value="{Hostname}:{ApplicationName} {Message}"/>
66
</appSettings>
77
<startup>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
namespace SyslogProxy
2+
{
3+
using System.Collections;
4+
using System.Configuration.Install;
5+
using System.Diagnostics;
6+
7+
public class EventSourceInstaller : Installer
8+
{
9+
public override void Install(IDictionary stateSaver)
10+
{
11+
if (!EventLog.SourceExists(Logger.EventSource))
12+
{
13+
EventLog.CreateEventSource(Logger.EventSource, "Application");
14+
}
15+
16+
base.Install(stateSaver);
17+
}
18+
19+
public override void Rollback(IDictionary savedState)
20+
{
21+
if (EventLog.SourceExists(Logger.EventSource))
22+
{
23+
24+
}
25+
26+
base.Rollback(savedState);
27+
}
28+
}
29+
}

src/SyslogProxy/Logger.cs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
namespace SyslogProxy
2+
{
3+
using System.Diagnostics;
4+
5+
public static class Logger
6+
{
7+
public const string EventSource = "SyslogProxy";
8+
9+
public static void Information(string message, params object[] args)
10+
{
11+
Information(string.Format(message, args));
12+
}
13+
14+
public static void Warning(string message, params object[] args)
15+
{
16+
Warning(string.Format(message, args));
17+
}
18+
19+
public static void Error(string message, params object[] args)
20+
{
21+
Error(string.Format(message, args));
22+
}
23+
24+
public static void Information(string message)
25+
{
26+
EventLog.WriteEntry(EventSource, message, EventLogEntryType.Information);
27+
}
28+
29+
public static void Warning(string message)
30+
{
31+
EventLog.WriteEntry(EventSource, message, EventLogEntryType.Warning);
32+
}
33+
34+
public static void Error(string message)
35+
{
36+
EventLog.WriteEntry(EventSource, message, EventLogEntryType.Error);
37+
}
38+
}
39+
}

src/SyslogProxy/Messages/JsonSyslogMessage.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public JsonSyslogMessage(string rawMessage)
3232
}
3333
catch (Exception)
3434
{
35-
Console.WriteLine("Could not parse priority. [{0}]", rawMessage);
35+
Logger.Warning("Could not parse priority. [{0}]", rawMessage);
3636
this.Invalid = true;
3737
return;
3838
}

src/SyslogProxy/Program.cs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,28 @@
11
namespace SyslogProxy
22
{
3-
using System.Threading;
3+
using System.Collections.Generic;
4+
using System.ComponentModel;
5+
using System.ServiceProcess;
46

5-
using SyslogProxy.Messages;
7+
using SimpleServices;
68

7-
public class Program
9+
[RunInstaller(true)]
10+
public class Program : SimpleServiceApplication
811
{
912
static void Main(string[] args)
1013
{
11-
var writer = new SeqWriter();
12-
13-
new Proxy(async message => await writer.WriteToSeq(new JsonSyslogMessage(message)).ConfigureAwait(false));
14-
15-
// TODO: do something better than loop endlessly
16-
while (true)
17-
{
18-
Thread.Sleep(100000);
19-
}
14+
new Service(args,
15+
new List<IWindowsService> { new ProxyService() }.ToArray,
16+
installationSettings: (serviceInstaller, serviceProcessInstaller) =>
17+
{
18+
serviceInstaller.ServiceName = "SyslogProxy";
19+
serviceInstaller.Description = "A simple Syslog proxy for Seq.";
20+
serviceInstaller.StartType = ServiceStartMode.Automatic;
21+
serviceProcessInstaller.Account = ServiceAccount.LocalService;
22+
serviceProcessInstaller.Installers.Add(new EventSourceInstaller());
23+
},
24+
configureContext: x => { x.Log = Logger.Information; })
25+
.Host();
2026
}
2127
}
2228
}

src/SyslogProxy/Proxy.cs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Net;
66
using System.Net.Sockets;
77
using System.Text;
8+
using System.Threading;
89
using System.Threading.Tasks;
910

1011
using SyslogProxy.Messages;
@@ -13,11 +14,14 @@ public class Proxy
1314
{
1415
private readonly Action<string> messageHandler;
1516

17+
private readonly CancellationToken cancellationToken;
18+
1619
private const int BufferSize = 2048;
1720

18-
public Proxy(Action<string> messageHandler)
21+
public Proxy(Action<string> messageHandler, CancellationToken cancellationToken)
1922
{
2023
this.messageHandler = messageHandler;
24+
this.cancellationToken = cancellationToken;
2125
var tcp = new TcpListener(IPAddress.Any, Configuration.ProxyPort);
2226

2327
tcp.Start();
@@ -26,7 +30,7 @@ public Proxy(Action<string> messageHandler)
2630

2731
private async Task AcceptConnection(TcpListener listener)
2832
{
29-
while (true)
33+
while (!this.cancellationToken.IsCancellationRequested)
3034
{
3135
var client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
3236
this.EchoAsync(client).ConfigureAwait(false);
@@ -35,7 +39,8 @@ private async Task AcceptConnection(TcpListener listener)
3539

3640
private async Task EchoAsync(TcpClient client)
3741
{
38-
Console.WriteLine("New client connected.");
42+
var ipAddress = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
43+
Logger.Information("New client connected from IP: [{0}].", ipAddress);
3944
using (client)
4045
{
4146
var stream = client.GetStream();
@@ -45,17 +50,16 @@ private async Task EchoAsync(TcpClient client)
4550
{
4651
var timeoutTask = Task.Delay(TimeSpan.FromSeconds(Configuration.TcpConnectionTimeout));
4752
Array.Clear(buf, 0, BufferSize);
48-
var amountReadTask = stream.ReadAsync(buf, 0, buf.Length);
53+
var amountReadTask = stream.ReadAsync(buf, 0, buf.Length, this.cancellationToken);
4954
var completedTask = await Task.WhenAny(timeoutTask, amountReadTask)
5055
.ConfigureAwait(false);
5156
if (completedTask == timeoutTask)
5257
{
53-
Console.WriteLine("Client timed out");
58+
Logger.Information("Client with IP [{0}] timed out.", ipAddress);
5459
break;
5560
}
5661

57-
var amountRead = amountReadTask.Result;
58-
if (amountRead == 0)
62+
if (amountReadTask.Result == 0)
5963
{
6064
break;
6165
}
@@ -69,7 +73,7 @@ private async Task EchoAsync(TcpClient client)
6973
}
7074
}
7175
}
72-
Console.WriteLine("Client disconnected");
76+
Logger.Information("Client with IP [{0}] disconnected.", ipAddress);
7377
}
7478
}
7579
}

src/SyslogProxy/ProxyService.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
namespace SyslogProxy
2+
{
3+
using System.Threading;
4+
5+
using SimpleServices;
6+
7+
using SyslogProxy.Messages;
8+
9+
public class ProxyService : IWindowsService
10+
{
11+
public ApplicationContext AppContext { get; set; }
12+
13+
private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
14+
15+
public void Start(string[] args)
16+
{
17+
var writer = new SeqWriter();
18+
new Proxy(async message => await writer.WriteToSeq(new JsonSyslogMessage(message)).ConfigureAwait(false),
19+
this.cancellationTokenSource.Token);
20+
}
21+
22+
public void Stop()
23+
{
24+
this.cancellationTokenSource.Cancel();
25+
}
26+
}
27+
}

src/SyslogProxy/SeqWriter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public async Task WriteToSeq(JsonSyslogMessage message, int delay = 0)
1616
{
1717
if (message.Invalid)
1818
{
19-
Console.WriteLine("Skipping incomplete/invalid message. [{0}]", message.RawMessage);
19+
Logger.Warning("Skipping incomplete/invalid message. [{0}]", message.RawMessage);
2020
return;
2121
}
2222

@@ -34,8 +34,8 @@ public async Task WriteToSeq(JsonSyslogMessage message, int delay = 0)
3434

3535
if (capturedException != null)
3636
{
37-
Console.Write("Couldn't write to SEQ. Exception: [{0}]", capturedException.SourceException.Message);
3837
this.retryCount++;
38+
Logger.Warning("Couldn't write to SEQ. Retry Count:[{0}] Exception: [{1}]", this.retryCount, capturedException.SourceException.Message);
3939
await this.WriteToSeq(message, (int)Math.Pow(100, this.retryCount));
4040
}
4141
}

src/SyslogProxy/SyslogProxy.csproj

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,23 +36,35 @@
3636
<SpecificVersion>False</SpecificVersion>
3737
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
3838
</Reference>
39+
<Reference Include="SimpleServices">
40+
<HintPath>..\..\packages\SimpleServices.2.0.12.0\lib\net45\SimpleServices.dll</HintPath>
41+
</Reference>
3942
<Reference Include="System" />
4043
<Reference Include="System.Configuration" />
44+
<Reference Include="System.Configuration.Install" />
4145
<Reference Include="System.Core" />
4246
<Reference Include="System.Net.Http" />
47+
<Reference Include="System.ServiceProcess" />
4348
<Reference Include="System.Xml.Linq" />
4449
<Reference Include="System.Data.DataSetExtensions" />
4550
<Reference Include="Microsoft.CSharp" />
4651
<Reference Include="System.Data" />
4752
<Reference Include="System.Xml" />
4853
</ItemGroup>
4954
<ItemGroup>
55+
<Compile Include="EventSourceInstaller.cs">
56+
<SubType>Component</SubType>
57+
</Compile>
58+
<Compile Include="Logger.cs" />
5059
<Compile Include="Messages\Configuration.cs" />
5160
<Compile Include="Messages\Facility.cs" />
5261
<Compile Include="Messages\SeqEventMessage.cs" />
62+
<Compile Include="ProxyService.cs" />
5363
<Compile Include="SeqWriter.cs" />
5464
<Compile Include="Messages\Severity.cs" />
55-
<Compile Include="Program.cs" />
65+
<Compile Include="Program.cs">
66+
<SubType>Component</SubType>
67+
</Compile>
5668
<Compile Include="Properties\AssemblyInfo.cs" />
5769
<Compile Include="Messages\JsonSyslogMessage.cs" />
5870
<Compile Include="Proxy.cs" />

src/SyslogProxy/packages.config

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<packages>
33
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
4+
<package id="SimpleServices" version="2.0.12.0" targetFramework="net45" />
45
</packages>

0 commit comments

Comments
 (0)