Add ILogger to GSIServer

This commit is contained in:
glax 2024-01-15 20:40:13 +01:00
parent b4b6f1dbb5
commit ab0e851996
2 changed files with 13 additions and 3 deletions

View File

@ -22,6 +22,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

View File

@ -1,5 +1,7 @@
using System.Net;
using System.Text;
using Microsoft.Extensions.Logging;
// ReSharper disable LocalizableElement
namespace CS2GSI;
@ -11,12 +13,16 @@ internal class GSIServer
internal event OnMessageEventHandler? OnMessage;
private bool _keepRunning = true;
internal bool IsRunning { get; private set; }
private ILogger? logger;
internal GSIServer(int port)
internal GSIServer(int port, ILogger? logger = null)
{
this.logger = logger;
string prefix = $"http://127.0.0.1:{port}/";
HttpListener = new HttpListener();
HttpListener.Prefixes.Add($"http://127.0.0.1:{port}/");
HttpListener.Prefixes.Add(prefix);
HttpListener.Start();
this.logger?.Log(LogLevel.Information, $"Listening on {prefix}");
Thread connectionListener = new (HandleConnection);
connectionListener.Start();
@ -31,7 +37,7 @@ internal class GSIServer
HttpListenerContext context = await HttpListener.GetContextAsync();
HttpListenerRequest request = context.Request;
Console.WriteLine($"[{request.HttpMethod}] {request.Url} - {request.UserAgent}");
this.logger?.Log(LogLevel.Information, $"[{request.HttpMethod}] {request.Url} - {request.UserAgent}");
HttpResponseMessage responseMessage = new (HttpStatusCode.Accepted);
context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(responseMessage.ToString()));
@ -39,13 +45,16 @@ internal class GSIServer
StreamReader reader = new (request.InputStream, request.ContentEncoding);
string content = await reader.ReadToEndAsync();
OnMessage?.Invoke(content);
this.logger?.Log(LogLevel.Debug, content);
}
HttpListener.Close();
IsRunning = false;
this.logger?.Log(LogLevel.Information, "Stopped GSIServer.");
}
internal void Dispose()
{
this.logger?.Log(LogLevel.Information, "Stopping GSIServer.");
_keepRunning = false;
}