Skip to content

Commit

Permalink
Remove Serilog Dependency.
Browse files Browse the repository at this point in the history
  • Loading branch information
HarryCordewener committed Jan 9, 2024
1 parent d02335e commit e0c352b
Show file tree
Hide file tree
Showing 25 changed files with 215 additions and 176 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Change Log
All notable changes to this project will be documented in this file.

## [1.0.4] - 2024-01-09

### Changed
- Removed Serilog dependency in favor of Microsoft.Extensions.Logging.Abstractions, which allows one to inject the preferred logger.

## [1.0.3] - 2024-01-08

### Fixed
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Initiate a logger. A Serilog logger is required by this library at this time.
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(new CompactJsonFormatter(), "LogResult.log")
.MinimumLevel.Debug()
.MinimumLevel.LogDebug()
.CreateLogger();

Log.Logger = log;
Expand All @@ -67,24 +67,24 @@ Create functions that implement your desired behavior on getting a signal.
}
catch(ObjectDisposedException ode)
{
_Logger.Information("Stream has been closed", ode);
_Logger.LogInformation("Stream has been closed", ode);
}
}

public static Task WriteBackAsync(byte[] writeback, Encoding encoding) =>
Task.Run(() => Console.WriteLine(encoding.GetString(writeback)));

public Task SignalGMCPAsync((string module, string writeback) val, Encoding encoding) =>
Task.Run(() => _Logger.Debug("GMCP Signal: {Module}: {WriteBack}", val.module, val.writeback));
Task.Run(() => _Logger.LogDebug("GMCP Signal: {Module}: {WriteBack}", val.module, val.writeback));

public Task SignalMSSPAsync(MSSPConfig val) =>
Task.Run(() => _Logger.Debug("New MSSP: {@MSSP}", val));
Task.Run(() => _Logger.LogDebug("New MSSP: {@MSSP}", val));

public Task SignalPromptAsync() =>
Task.Run(() => _Logger.Debug("Prompt"));
Task.Run(() => _Logger.LogDebug("Prompt"));

public Task SignalNAWSAsync(int height, int width) =>
Task.Run(() => _Logger.Debug("Client Height and Width updated: {Height}x{Width}", height, width));
Task.Run(() => _Logger.LogDebug("Client Height and Width updated: {Height}x{Width}", height, width));
```

Initialize the Interpreter.
Expand Down
22 changes: 8 additions & 14 deletions TelnetNegotiationCore.TestClient/MockPipelineClient.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
using Serilog;
using System.Net.Sockets;
using System.Net.Sockets;
using TelnetNegotiationCore.Interpreters;
using System.IO.Pipelines;
using Pipelines.Sockets.Unofficial;
using System.Text;
using TelnetNegotiationCore.Models;
using System.Collections.Immutable;
using Microsoft.Extensions.Logging;

namespace TelnetNegotiationCore.TestClient
{
public class MockPipelineClient
public class MockPipelineClient(ILogger<MockPipelineClient> logger)
{
readonly ILogger _Logger;

public MockPipelineClient()
{
_Logger = Log.Logger.ForContext<MockPipelineClient>();
}

private async Task WriteToOutputStreamAsync(byte[] arg, PipeWriter writer)
{
Expand All @@ -26,7 +20,7 @@ private async Task WriteToOutputStreamAsync(byte[] arg, PipeWriter writer)
}
catch (ObjectDisposedException ode)
{
_Logger.Information("Stream has been closed", ode);
logger.LogError(ode, "Stream has been closed");
}
}

Expand All @@ -35,26 +29,26 @@ public static Task WriteBackAsync(byte[] writeback, Encoding encoding, TelnetInt

public Task SignalGMCPAsync((string module, string writeback) val)
{
_Logger.Debug("GMCP Signal: {Module}: {WriteBack}", val.module, val.writeback);
logger.LogDebug("GMCP Signal: {Module}: {WriteBack}", val.module, val.writeback);
return Task.CompletedTask;
}

public Task SignalMSSPAsync(MSSPConfig val)
{
_Logger.Debug("New MSSP: {@MSSPConfig}", val);
logger.LogDebug("New MSSP: {@MSSPConfig}", val);
return Task.CompletedTask;
}

public Task SignalPromptAsync() =>
Task.Run(() => _Logger.Debug("Prompt"));
Task.Run(() => logger.LogDebug("Prompt"));

public async Task StartAsync(string address, int port)
{
var client = new TcpClient(address, port);
var stream = client.GetStream();
var pipe = StreamConnection.GetDuplex(stream, new PipeOptions());

var telnet = await new TelnetInterpreter(TelnetInterpreter.TelnetMode.Client, _Logger.ForContext<TelnetInterpreter>())
var telnet = await new TelnetInterpreter(TelnetInterpreter.TelnetMode.Client, logger)
{
CallbackOnSubmitAsync = WriteBackAsync,
CallbackNegotiationAsync = (x) => WriteToOutputStreamAsync(x, pipe.Output),
Expand Down
26 changes: 20 additions & 6 deletions TelnetNegotiationCore.TestClient/Program.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
using Serilog;
using Serilog.Formatting.Compact;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;

namespace TelnetNegotiationCore.TestClient
{
public class Program
{
static async Task Main()
static async Task Main(string[] args)
{
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.File(new CompactJsonFormatter(), "LogResult.log")
.WriteTo.Console()
.MinimumLevel.Debug()
.CreateLogger();

Log.Logger = log;
var client = new MockPipelineClient();
await client.StartAsync("127.0.0.1", 4201);

var builder = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddTransient<MockPipelineClient>();
});

var host = builder.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddSerilog();
logging.SetMinimumLevel(LogLevel.Debug);
}).Build();

await host.Services.GetRequiredService<MockPipelineClient>().StartAsync("127.0.0.1", 4201);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageReference Include="Pipelines.Sockets.Unofficial" Version="2.2.8" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="System.IO.Pipelines" Version="8.0.0" />
</ItemGroup>

Expand Down
86 changes: 44 additions & 42 deletions TelnetNegotiationCore.TestServer/KestrelMockServer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Serilog;
using System;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
Expand All @@ -9,17 +8,18 @@
using Microsoft.AspNetCore.Connections;
using System.IO.Pipelines;
using System.Collections.Immutable;
using Microsoft.Extensions.Logging;

namespace TelnetNegotiationCore.TestServer
{
public class KestrelMockServer : ConnectionHandler
{
private readonly ILogger _Logger;

public KestrelMockServer(ILogger logger = null) : base()
public KestrelMockServer(ILogger<KestrelMockServer> logger) : base()
{
Console.OutputEncoding = Encoding.UTF8;
_Logger = logger ?? Log.Logger.ForContext<KestrelMockServer>();
_Logger = logger;
}

private async Task WriteToOutputStreamAsync(byte[] arg, PipeWriter writer)
Expand All @@ -30,25 +30,25 @@ private async Task WriteToOutputStreamAsync(byte[] arg, PipeWriter writer)
}
catch (ObjectDisposedException ode)
{
_Logger.Information("Stream has been closed", ode);
_Logger.LogError(ode, "Stream has been closed");
}
}

public Task SignalGMCPAsync((string module, string writeback) val)
{
_Logger.Debug("GMCP Signal: {Module}: {WriteBack}", val.module, val.writeback);
_Logger.LogDebug("GMCP Signal: {Module}: {WriteBack}", val.module, val.writeback);
return Task.CompletedTask;
}

public Task SignalMSSPAsync(MSSPConfig val)
{
_Logger.Debug("New MSSP: {@MSSPConfig}", val);
_Logger.LogDebug("New MSSP: {@MSSPConfig}", val);
return Task.CompletedTask;
}

public Task SignalNAWSAsync(int height, int width)
{
_Logger.Debug("Client Height and Width updated: {Height}x{Width}", height, width);
_Logger.LogDebug("Client Height and Width updated: {Height}x{Width}", height, width);
return Task.CompletedTask;
}

Expand All @@ -64,49 +64,51 @@ public static async Task WriteBackAsync(byte[] writeback, Encoding encoding, Tel

public async override Task OnConnectedAsync(ConnectionContext connection)
{
_Logger.Information(connection.ConnectionId + " connected");

var telnet = await new TelnetInterpreter(TelnetInterpreter.TelnetMode.Server)
using (_Logger.BeginScope(new Dictionary<string, object> { { "ConnectionId", connection.ConnectionId } }))
{
CallbackOnSubmitAsync = (w, e, t) => WriteBackAsync(w, e, t),
SignalOnGMCPAsync = SignalGMCPAsync,
SignalOnMSSPAsync = SignalMSSPAsync,
SignalOnNAWSAsync = SignalNAWSAsync,
CallbackNegotiationAsync = (x) => WriteToOutputStreamAsync(x, connection.Transport.Output),
CharsetOrder = new[] { Encoding.GetEncoding("utf-8"), Encoding.GetEncoding("iso-8859-1") }
}
.RegisterMSSPConfig(() => new MSSPConfig
{
Name = "My Telnet Negotiated Server",
UTF_8 = true,
Gameplay = ["ABC", "DEF"],
Extended = new Dictionary<string, dynamic>
_Logger.LogInformation("{ConnectionId} connected", connection.ConnectionId);

var telnet = await new TelnetInterpreter(TelnetInterpreter.TelnetMode.Server, _Logger)
{
CallbackOnSubmitAsync = (w, e, t) => WriteBackAsync(w, e, t),
SignalOnGMCPAsync = SignalGMCPAsync,
SignalOnMSSPAsync = SignalMSSPAsync,
SignalOnNAWSAsync = SignalNAWSAsync,
CallbackNegotiationAsync = (x) => WriteToOutputStreamAsync(x, connection.Transport.Output),
CharsetOrder = new[] { Encoding.GetEncoding("utf-8"), Encoding.GetEncoding("iso-8859-1") }
}
.RegisterMSSPConfig(() => new MSSPConfig
{
Name = "My Telnet Negotiated Server",
UTF_8 = true,
Gameplay = ["ABC", "DEF"],
Extended = new Dictionary<string, dynamic>
{
{ "Foo", "Bar"},
{ "Baz", (string[])["Moo", "Meow"] }
}
})
.BuildAsync();

while (true)
{
var result = await connection.Transport.Input.ReadAsync();
var buffer = result.Buffer;
}
})
.BuildAsync();

foreach (var segment in buffer)
while (true)
{
await telnet.InterpretByteArrayAsync(segment.Span.ToImmutableArray());
}
var result = await connection.Transport.Input.ReadAsync();
var buffer = result.Buffer;

if (result.IsCompleted)
{
break;
}
foreach (var segment in buffer)
{
await telnet.InterpretByteArrayAsync(segment.Span.ToImmutableArray());
}

connection.Transport.Input.AdvanceTo(buffer.End);
}
if (result.IsCompleted)
{
break;
}

_Logger.Information(connection.ConnectionId + " disconnected");
connection.Transport.Input.AdvanceTo(buffer.End);
}
_Logger.LogInformation("{ConnectionId} disconnected", connection.ConnectionId);
}
}
}
}
7 changes: 3 additions & 4 deletions TelnetNegotiationCore.TestServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Formatting.Compact;
using System.Threading.Tasks;

namespace TelnetNegotiationCore.TestServer
Expand All @@ -14,7 +14,6 @@ static async Task Main(string[] args)
var log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(new CompactJsonFormatter(), "LogResult.log")
.MinimumLevel.Debug()
.CreateLogger();

Expand All @@ -26,7 +25,7 @@ static async Task Main(string[] args)

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => options.ListenLocalhost(4202, builder => builder.UseConnectionHandler<KestrelMockServer>()))
.UseStartup<Startup>();
.UseStartup<Startup>()
.UseKestrel(options => options.ListenLocalhost(4202, builder => builder.UseConnectionHandler<KestrelMockServer>()));
}
}
13 changes: 12 additions & 1 deletion TelnetNegotiationCore.TestServer/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Threading.Tasks;

namespace TelnetNegotiationCore.TestServer
Expand All @@ -9,7 +11,16 @@ public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public static void ConfigureServices(IServiceCollection _) { }
public static void ConfigureServices(IServiceCollection services)
{
services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddSerilog();
logging.SetMinimumLevel(LogLevel.Debug);
});
services.BuildServiceProvider();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public static void Configure(IApplicationBuilder app, IHostingEnvironment _) => app.Run(async _ => await Task.CompletedTask);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading

0 comments on commit e0c352b

Please sign in to comment.