diff --git a/CS2GSI.csproj b/CS2GSI.csproj index 49fa879..1ec8b1f 100644 --- a/CS2GSI.csproj +++ b/CS2GSI.csproj @@ -22,6 +22,7 @@ + diff --git a/GSIServer.cs b/GSIServer.cs index 8f909d9..c8c91ab 100644 --- a/GSIServer.cs +++ b/GSIServer.cs @@ -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; }