Skip to content

Commit

Permalink
Tear down dependencies on loggers (#389)
Browse files Browse the repository at this point in the history
* Tear down dependencies on loggers

* This looks nicer
  • Loading branch information
Jonpro03 authored Sep 15, 2023
1 parent 1d6b40b commit ad42e78
Show file tree
Hide file tree
Showing 31 changed files with 98 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using Microsoft.Extensions.Logging;
using Obsidian.API;
using Obsidian.Utilities;
using Obsidian.API.Utilities;
using System.Diagnostics;

namespace Obsidian.ConsoleApp.Logging;
namespace Obsidian.API.Logging;

public class Logger : ILogger<Server>
public class Logger : ILogger
{
protected static readonly object _lock = new();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;

namespace Obsidian.ConsoleApp.Logging;
namespace Obsidian.API.Logging;

public sealed class LoggerProvider : ILoggerProvider
public class LoggerProvider : ILoggerProvider
{
private ConcurrentDictionary<string, Logger> loggers = new();

private LogLevel MinimumLevel { get; }

private bool disposed = false;

internal LoggerProvider(LogLevel minLevel = LogLevel.Information)
public LoggerProvider(LogLevel minLevel = LogLevel.Information)
{
MinimumLevel = minLevel;
}
Expand Down
1 change: 1 addition & 0 deletions Obsidian.API/Obsidian.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="SharpNoise" Version="0.12.1.1" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Threading;

namespace Obsidian.Utilities;
namespace Obsidian.API.Utilities;

/// <summary>
/// Allows simultaneous console input and output without breaking user input
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Obsidian.Utilities;
namespace Obsidian.API.Utilities;

public static partial class Extensions
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;

namespace Obsidian.Utilities;
namespace Obsidian.API.Utilities;

public static partial class Extensions
{
Expand Down
2 changes: 1 addition & 1 deletion Obsidian.API/Utilities/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Diagnostics;

namespace Obsidian.API.Utilities;
public static class Extensions
public static partial class Extensions
{
public static List<string> GetStateValues(this string key, Dictionary<string, string[]> valueStores)
{
Expand Down
4 changes: 2 additions & 2 deletions Obsidian.ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Obsidian.ConsoleApp.Logging;
using Obsidian.API.Logging;
using Obsidian.API.Utilities;
using Obsidian.Hosting;
using Obsidian.Utilities;

namespace Obsidian.ConsoleApp;

Expand Down
9 changes: 7 additions & 2 deletions Obsidian/Client.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;
using Obsidian.API.Events;
using Obsidian.API.Logging;
using Obsidian.API.Utilities;
using Obsidian.Concurrency;
using Obsidian.Entities;
using Obsidian.Events.EventArgs;
Expand Down Expand Up @@ -148,7 +150,7 @@ public sealed class Client : IDisposable
/// <summary>
/// Used to log actions caused by the client.
/// </summary>
public ILogger Logger => Server.Logger;
protected ILogger Logger { get; private set; }

/// <summary>
/// The player that the client is logged in as.
Expand All @@ -169,6 +171,9 @@ public Client(ConnectionContext connectionContext, ServerConfiguration config, i
{
this.connectionContext = connectionContext;
this.config = config;
var loggerProvider = new LoggerProvider(config.LogLevel);
Logger = loggerProvider.CreateLogger("Client");

id = playerId;
Server = originServer;

Expand Down Expand Up @@ -575,7 +580,7 @@ internal void HandleKeepAlive(KeepAlivePacket keepAlive)
{
if (!missedKeepAlives.Contains(keepAlive.KeepAliveId))
{
Server.Logger.LogWarning($"Received invalid KeepAlive from {Player.Username}?? Naughty???? ({Player.Uuid})");
Logger.LogWarning($"Received invalid KeepAlive from {Player.Username}?? Naughty???? ({Player.Uuid})");
DisconnectAsync(ChatMessage.Simple("Kicked for invalid KeepAlive."));
return;
}
Expand Down
1 change: 1 addition & 0 deletions Obsidian/Commands/MainCommandModule.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Obsidian.API.Utilities;
using Obsidian.Commands.Framework.Entities;
using Obsidian.Entities;
using Obsidian.Registries;
Expand Down
17 changes: 14 additions & 3 deletions Obsidian/Entities/Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// https://wiki.vg/Map_Format
using Microsoft.Extensions.Logging;
using Obsidian.API.Events;
using Obsidian.API.Logging;
using Obsidian.API.Utilities;
using Obsidian.Nbt;
using Obsidian.Net;
using Obsidian.Net.Actions.PlayerInfo;
Expand All @@ -14,6 +16,7 @@
using System.IO;
using System.Linq;
using System.Net;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace Obsidian.Entities;

Expand All @@ -24,6 +27,11 @@ public sealed partial class Player : Living, IPlayer

internal readonly Client client;

/// <summary>
/// Used to log actions caused by the client.
/// </summary>
protected ILogger Logger { get; private set; }

internal HashSet<int> visiblePlayers = new();

//TODO: better name??
Expand Down Expand Up @@ -115,6 +123,9 @@ internal Player(Guid uuid, string username, Client client, World world)
Username = username;
this.client = client;
EntityId = client.id;
var loggerProvider = new LoggerProvider();
Logger = loggerProvider.CreateLogger("Player");

Inventory = new Container(9 * 5 + 1, InventoryType.Generic)
{
Owner = uuid,
Expand Down Expand Up @@ -334,7 +345,7 @@ public async Task RespawnAsync(DataKept dataKept = DataKept.Metadata)
CodecRegistry.TryGetDimension(world.DimensionName, out var codec);
Debug.Assert(codec is not null); // TODO Handle missing codec

server.Logger.LogDebug("Loading into world: {}", world.Name);
Logger.LogDebug("Loading into world: {}", world.Name);

await client.QueuePacketAsync(new RespawnPacket
{
Expand Down Expand Up @@ -650,12 +661,12 @@ public async Task LoadAsync(bool loadFromPersistentWorld = true)
{
var worldName = persistentDataCompound.GetString("worldName");

server.Logger.LogInformation($"persistent world: {worldName}");
Logger.LogInformation($"persistent world: {worldName}");

if (loadFromPersistentWorld && server.WorldManager.TryGetWorld(worldName, out var world))
{
base.world = world;
server.Logger.LogInformation($"Loading from persistent world: {worldName}");
Logger.LogInformation($"Loading from persistent world: {worldName}");
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion Obsidian/Globals.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Obsidian.Utilities.Converters;
using Obsidian.API.Utilities;
using Obsidian.Utilities.Converters;
using System.Net.Http;
using System.Text.Encodings.Web;
using System.Text.Json;
Expand Down
3 changes: 2 additions & 1 deletion Obsidian/Net/MinecraftStream.Reading.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Obsidian.Commands;
using Obsidian.API.Utilities;
using Obsidian.Commands;
using Obsidian.Nbt;
using Obsidian.Registries;
using Obsidian.Serialization.Attributes;
Expand Down
2 changes: 1 addition & 1 deletion Obsidian/Net/MinecraftStream.Writing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Obsidian.API.Crafting;
using Obsidian.API.Inventory;
using Obsidian.API.Registry.Codecs.Dimensions;
using Obsidian.API.Utilities;
using Obsidian.Commands;
using Obsidian.Entities;
using Obsidian.Nbt;
Expand All @@ -12,7 +13,6 @@
using Obsidian.Registries;
using Obsidian.Serialization.Attributes;
using System.Buffers.Binary;
using System.Diagnostics.CodeAnalysis;
using System.Text;

namespace Obsidian.Net;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Obsidian.Nbt;
using Obsidian.API.Utilities;
using Obsidian.Nbt;
using Obsidian.WorldData;

namespace Obsidian.Net.Packets.Play.Clientbound;
Expand Down
7 changes: 5 additions & 2 deletions Obsidian/Net/Packets/Play/Serverbound/ChatCommandPacket.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Obsidian.API.Logging;
using Obsidian.Commands;
using Obsidian.Commands.Framework.Entities;
using Obsidian.Entities;
Expand Down Expand Up @@ -27,14 +28,16 @@ public partial class ChatCommandPacket : IServerboundPacket

public async ValueTask HandleAsync(Server server, Player player)
{
var context = new CommandContext($"/{this.Command}", new CommandSender(CommandIssuers.Client, player, server.Logger), player, server);
var loggerProvider = new LoggerProvider(LogLevel.Error);
var logger = loggerProvider.CreateLogger("ChatCommandPacket");
var context = new CommandContext($"/{this.Command}", new CommandSender(CommandIssuers.Client, player, logger), player, server);
try
{
await server.CommandsHandler.ProcessCommand(context);
}
catch (Exception e)
{
server.Logger.LogError(e, e.Message);
logger.LogError(e, e.Message);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,6 @@ private async Task HandleMouseClick(BaseContainer container, Server server, Play
{
if (Button == 0)
{
server.Logger.LogDebug("Placed: {} in container: {}", player.LastClickedItem?.Type, container.Title?.Text);
container.SetItem(slot, player.LastClickedItem);

player.LastClickedItem = CarriedItem;
Expand Down
1 change: 1 addition & 0 deletions Obsidian/Registries/ItemsRegistry.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Obsidian.API.Crafting;
using Obsidian.API.Utilities;

namespace Obsidian.Registries;
public partial class ItemsRegistry
Expand Down
5 changes: 4 additions & 1 deletion Obsidian/ScoreboardManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Obsidian.API.Logging;

namespace Obsidian;

Expand All @@ -19,8 +20,10 @@ public ScoreboardManager(Server server)

public IScoreboard CreateScoreboard(string name)
{
var loggerProvider = new LoggerProvider(LogLevel.Warning);
var logger = loggerProvider.CreateLogger("ScoreboardManager");
if (!this.scoreboards.Add(name))
this.server.Logger.LogWarning($"Scoreboard with the name: {name} already exists. This might cause some issues and override already existing scoreboards displaying on clients.");
logger.LogWarning($"Scoreboard with the name: {name} already exists. This might cause some issues and override already existing scoreboards displaying on clients.");

return new Scoreboard(name, this.server);
}
Expand Down
1 change: 1 addition & 0 deletions Obsidian/Server.Events.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Obsidian.API.Builders;
using Obsidian.API.Containers;
using Obsidian.API.Events;
using Obsidian.API.Utilities;
using Obsidian.Entities;
using Obsidian.Nbt;
using Obsidian.Net.Packets.Play.Clientbound;
Expand Down
12 changes: 6 additions & 6 deletions Obsidian/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using Obsidian.API.Builders;
using Obsidian.API.Crafting;
using Obsidian.API.Events;
using Obsidian.API.Logging;
using Obsidian.API.Utilities;
using Obsidian.Commands;
using Obsidian.Commands.Framework;
using Obsidian.Commands.Framework.Entities;
Expand Down Expand Up @@ -91,9 +93,6 @@ public static string VERSION
public IWorld DefaultWorld => WorldManager.DefaultWorld;
public IEnumerable<IPlayer> Players => GetPlayers();

// TODO: This should be removed. Services should get their own logger.
public ILogger Logger => _logger;

/// <summary>
/// Creates a new instance of <see cref="Server"/>.
/// </summary>
Expand All @@ -103,13 +102,14 @@ public Server(
ILogger<Server> logger,
RconServer rconServer)
{
_logger = logger;
Config = environment.Configuration;
var loggerProvider = new LoggerProvider(Config.LogLevel);
_logger = loggerProvider.CreateLogger("Server");
_logger.LogInformation($"SHA / Version: {VERSION}");
_cancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(lifetime.ApplicationStopping);
_cancelTokenSource.Token.Register(() => _logger.LogWarning("Obsidian is shutting down..."));
_rconServer = rconServer;

Config = environment.Configuration;
Port = Config.Port;
ServerFolderPath = Directory.GetCurrentDirectory();

Expand Down Expand Up @@ -377,7 +377,7 @@ private async Task AcceptClientsAsync()
if (throttler.TryGetValue(ip, out var time) && time <= DateTimeOffset.UtcNow)
{
throttler.Remove(ip, out _);
this.Logger.LogDebug("Removed {ip} from throttler", ip);
_logger.LogDebug("Removed {ip} from throttler", ip);
}
}

Expand Down
10 changes: 7 additions & 3 deletions Obsidian/Utilities/ClientHandler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Obsidian.API.Logging;
using Obsidian.Net.Packets;
using Obsidian.Net.Packets.Play;
using Obsidian.Net.Packets.Play.Clientbound;
Expand All @@ -11,10 +12,13 @@ public class ClientHandler
{
private ConcurrentDictionary<int, IServerboundPacket> Packets { get; } = new ConcurrentDictionary<int, IServerboundPacket>();
private ServerConfiguration config;
private readonly ILogger _logger;

public ClientHandler(ServerConfiguration config)
{
this.config = config;
var loggerProvider = new LoggerProvider(LogLevel.Error);
_logger = loggerProvider.CreateLogger("ClientHanlder");
}

public void RegisterHandlers()
Expand Down Expand Up @@ -165,13 +169,13 @@ public async Task HandlePlayPackets(int id, byte[] data, Client client)
catch (Exception e)
{
if (this.config.VerboseExceptionLogging)
client.Logger.LogError(e.Message + Environment.NewLine + e.StackTrace);
_logger.LogError(e.Message + Environment.NewLine + e.StackTrace);
}
break;
}
}

private static async Task HandleFromPoolAsync<T>(byte[] data, Client client) where T : IServerboundPacket, new()
private async Task HandleFromPoolAsync<T>(byte[] data, Client client) where T : IServerboundPacket, new()
{
var packet = ObjectPool<T>.Shared.Rent();
try
Expand All @@ -182,7 +186,7 @@ public async Task HandlePlayPackets(int id, byte[] data, Client client)
catch (Exception e)
{
if (client.Server.Config.VerboseExceptionLogging)
client.Logger.LogError(e.Message + Environment.NewLine + e.StackTrace);
_logger.LogError(e.Message + Environment.NewLine + e.StackTrace);
}
ObjectPool<T>.Shared.Return(packet);
}
Expand Down
1 change: 1 addition & 0 deletions Obsidian/Utilities/Converters/DefaultEnumConverter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Obsidian.API.Crafting;
using Obsidian.API.Utilities;
using System.Text.Json;
using System.Text.Json.Serialization;

Expand Down
1 change: 1 addition & 0 deletions Obsidian/Utilities/Converters/IngredientConverter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Obsidian.API.Crafting;
using Obsidian.API.Utilities;
using Obsidian.Registries;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down
Loading

0 comments on commit ad42e78

Please sign in to comment.