Skip to content

Commit

Permalink
Added Serilog
Browse files Browse the repository at this point in the history
  • Loading branch information
DrMeepso committed Dec 5, 2024
1 parent b7fdc8a commit 359b488
Show file tree
Hide file tree
Showing 13 changed files with 159 additions and 82 deletions.
3 changes: 3 additions & 0 deletions Cove/Cove.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Steamworks.NET" Version="2024.8.0" />
</ItemGroup>

Expand Down
12 changes: 7 additions & 5 deletions Cove/GodotFormat/GDReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ public class GodotReader

public byte[] data;
private BinaryReader reader;
public Serilog.Core.Logger logger;

public GodotReader(byte[] data)
public GodotReader(byte[] data, Serilog.Core.Logger serverLogger)
{
this.data = data;
reader = new BinaryReader(new MemoryStream(data), System.Text.Encoding.UTF8);
logger = serverLogger;
}

public Dictionary<string, object> readPacket()
Expand All @@ -46,8 +48,8 @@ public Dictionary<string, object> readPacket()
}
catch (Exception e)
{
Console.WriteLine("-- Error reading packet! --"); // incase we do have a error!
Console.WriteLine(e.ToString()); // incase we do have a error!
logger.Error("-- Error reading packet! --"); // incase we do have a error!
logger.Error(e.ToString()); // incase we do have a error!
}

return dic;
Expand Down Expand Up @@ -96,7 +98,7 @@ private Object readNext()
return readVector2();

default:
Console.WriteLine($"Unable to handel object of type: {type}");
logger.Error($"Unable to handel object of type: {type}");
return new ReadError();
}
}
Expand Down Expand Up @@ -214,7 +216,7 @@ private Dictionary<string, object> readDictionary()

if (keyValue == null || !(keyValue is String)) // if the value is not a string (bad read) break the loop.
{
Console.WriteLine("READ ERROR, KEY PROVIDED IS NOT A STRING!");
logger.Error("READ ERROR, KEY PROVIDED IS NOT A STRING!");
break; //break from the loop to save the server!
}
else
Expand Down
65 changes: 44 additions & 21 deletions Cove/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,37 @@ limitations under the License.
using Cove.Server;
using Cove.Server.Actor;
using Steamworks;
using Serilog;

var serverLogger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) // Daily rolling logs
.CreateLogger();

//Console.SetOut(new SerilogTextWriter(serverLogger));
//Console.SetError(new SerilogTextWriter(serverLogger, true));

CoveServer webfishingServer = new CoveServer();
webfishingServer.Init(); // start the server
webfishingServer.logger = serverLogger;
try
{
serverLogger.Information("Starting server...");
webfishingServer.Init(); // start the server
} catch (Exception e)
{
serverLogger.Fatal("Error occored on main thread");
serverLogger.Fatal(e.ToString());
}

void Log(string message)
{
serverLogger.Information(message);
}

Console.CancelKeyPress += Console_CancelKeyPress;
void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Application is closing...");
Log("Application is closing...");

Dictionary<string, object> closePacket = new();
closePacket["type"] = "server_close";
Expand All @@ -44,7 +67,7 @@ void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
switch(command)
{
case "exit":
Console.WriteLine("Application is closing...");
Log("Application is closing...");
Dictionary<string, object> closePacket = new();
closePacket["type"] = "server_close";

Expand All @@ -59,7 +82,7 @@ void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
string message = input.Substring(command.Length + 1);
webfishingServer.messageGlobal($"Server: {message}");
Console.WriteLine($"Server: {message}");
Log($"Server: {message}");
}
break;
case "ban":
Expand All @@ -70,17 +93,17 @@ void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
if (webfishingServer.isPlayerBanned(player.SteamId))
{
Console.WriteLine($"Player {player.Username} is already banned!");
Log($"Player {player.Username} is already banned!");
break;
} else
{
webfishingServer.banPlayer(player.SteamId, true);
}
Console.WriteLine($"Banned player {player.Username}");
Log($"Banned player {player.Username}");
}
else
{
Console.WriteLine("Player not found!");
Log("Player not found!");
}
}
break;
Expand All @@ -91,34 +114,34 @@ void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
if (player != null)
{
webfishingServer.kickPlayer(player.SteamId);
Console.WriteLine($"Kicked player {player.Username}");
Log($"Kicked player {player.Username}");
}
else
{
Console.WriteLine("Player not found!");
Log("Player not found!");
}
}
break;
case "players":
Console.WriteLine("Players:");
Log("Players:");
foreach (WFPlayer player in webfishingServer.AllPlayers)
{
Console.WriteLine(player.Username);
Log(player.Username);
}
break;
case "help":
Console.WriteLine("Commands:");
Console.WriteLine("exit - Closes the application");
Console.WriteLine("say <message> - Sends a message to all players");
Console.WriteLine("ban <player> - Bans a player");
Console.WriteLine("kick <player> - Kicks a player");
Console.WriteLine("help - Shows this message");
Console.WriteLine("players - Lists all players");
Console.WriteLine("");
Console.WriteLine("players are the username of the player");
Log("Commands:");
Log("exit - Closes the application");
Log("say <message> - Sends a message to all players");
Log("ban <player> - Bans a player");
Log("kick <player> - Kicks a player");
Log("help - Shows this message");
Log("players - Lists all players");
Log("");
Log("players are the username of the player");
break;
default:
Console.WriteLine("Unknown command! Type 'help' for a list of commands.");
Log("Unknown command! Type 'help' for a list of commands.");
break;
}

Expand Down
36 changes: 36 additions & 0 deletions Cove/SerilogTextWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.IO;
using System.Text;
using Serilog;

public class SerilogTextWriter : TextWriter
{
private readonly ILogger _logger;
private readonly bool _isError;

public SerilogTextWriter(ILogger logger, bool isError = false)
{
_logger = logger;
_isError = isError;
}

public override Encoding Encoding => Encoding.UTF8;

public override void WriteLine(string? value)
{
if (_isError)
{
_logger.Error(value);

Check warning on line 23 in Cove/SerilogTextWriter.cs

View workflow job for this annotation

GitHub Actions / linux-build

Possible null reference argument for parameter 'messageTemplate' in 'void ILogger.Error(string messageTemplate)'.

Check warning on line 23 in Cove/SerilogTextWriter.cs

View workflow job for this annotation

GitHub Actions / windows-build

Possible null reference argument for parameter 'messageTemplate' in 'void ILogger.Error(string messageTemplate)'.
}
else
{
_logger.Information(value);

Check warning on line 27 in Cove/SerilogTextWriter.cs

View workflow job for this annotation

GitHub Actions / linux-build

Possible null reference argument for parameter 'messageTemplate' in 'void ILogger.Information(string messageTemplate)'.

Check warning on line 27 in Cove/SerilogTextWriter.cs

View workflow job for this annotation

GitHub Actions / windows-build

Possible null reference argument for parameter 'messageTemplate' in 'void ILogger.Information(string messageTemplate)'.
}
}

public override void Write(char value)
{
// Optional: buffer single-character writes if needed.
WriteLine(value.ToString());
}
}
3 changes: 2 additions & 1 deletion Cove/Server/HostedServices/ActorUpdate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ private void DoWork(object state)
}
catch (InvalidOperationException e)
{
//Console.WriteLine(e);
_logger.LogError(e.ToString());
//Log(e);
// just means the list was modified while iterating
// most likly a actor was added or removed because of a spawn or despawn
// nothing to worry about
Expand Down
2 changes: 1 addition & 1 deletion Cove/Server/HostedServices/HostSpawn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ private void DoWork(object state)
if (inst.despawn && instanceAge >= inst.despawnTime)
{
server.removeServerActor(inst);
//Console.WriteLine($"Removed {inst.Type}, Decayed");
//Log($"Removed {inst.Type}, Decayed");
}
}
}
Expand Down
24 changes: 13 additions & 11 deletions Cove/Server/Plugins/Server.Plugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,18 @@ protected void loadAllPlugins()

if (!arePluginsEnabled) return; // plugins are disabled!

Console.WriteLine("\n------------ WARNING ------------");
Console.WriteLine("YOU HAVE ENABLED PLUGINS, PLUGINS RUN CODE THAT IS NOT APPROVED OR MADE BY COVE");
Console.WriteLine("ANY AND ALL DAMMAGE TO YOUR COMPUTER IS YOU AND YOUR FAULT ALONE");
Console.WriteLine("DO NOT RUN ANY UNTRUSTED PLUGINS!");
Console.WriteLine("IF YOU ARE RUNNING UNTRUSTED PLUGINS EXIT COVE NOW");
Console.WriteLine("------------ WARNING ------------\n");
Log("");
Log("------------ WARNING ------------");
Log("YOU HAVE ENABLED PLUGINS, PLUGINS RUN CODE THAT IS NOT APPROVED OR MADE BY COVE");
Log("ANY AND ALL DAMMAGE TO YOUR COMPUTER IS YOU AND YOUR FAULT ALONE");
Log("DO NOT RUN ANY UNTRUSTED PLUGINS!");
Log("IF YOU ARE RUNNING UNTRUSTED PLUGINS EXIT COVE NOW");
Log("------------ WARNING ------------");
Log("");

Thread.Sleep(5000);

Console.WriteLine("Loading Plugins...");
Log("Loading Plugins...");

string pluginsFolder = $"{AppDomain.CurrentDomain.BaseDirectory}plugins";

Expand All @@ -39,11 +41,11 @@ protected void loadAllPlugins()
}
catch (BadImageFormatException)
{
Console.WriteLine($"File: {fileName} is not a plugin!");
Log($"File: {fileName} is not a plugin!");
}
}

Console.WriteLine($"Found {pluginAssemblys.Count} plugins!");
Log($"Found {pluginAssemblys.Count} plugins!");

foreach (Assembly assembly in pluginAssemblys)
{
Expand All @@ -65,11 +67,11 @@ protected void loadAllPlugins()
PluginInstance thisInstance = new(plugin, config["name"], config["id"], config["author"]);

loadedPlugins.Add(thisInstance);
Console.WriteLine($"Plugin Init: {config["name"]}");
Log($"Plugin Init: {config["name"]}");
plugin.onInit(); // start the plugin!
}
else
Console.WriteLine($"Unable to load {type.FullName}");
Log($"Unable to load {type.FullName}");
}
}
}
Expand Down
10 changes: 6 additions & 4 deletions Cove/Server/Server.Packet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ void OnNetworkPacket(byte[] packet, CSteamID sender)
string type = (string)((Dictionary<string, object>)packetInfo["params"])["actor_type"];
long actorID = (long)((Dictionary<string, object>)packetInfo["params"])["actor_id"];

Log($"Player spawned in a {type} actor");

// all actor types that should not be spawned by anyone but the server!
if (type == "fish_spawn_alien" || type == "fish_spawn" || type == "raincloud")
{
Expand All @@ -87,7 +89,7 @@ void OnNetworkPacket(byte[] packet, CSteamID sender)
{
WFPlayer thisPlayer = AllPlayers.Find(p => p.SteamId.m_SteamID == sender.m_SteamID);
if (thisPlayer == null)
Console.WriteLine("No fisher found for player instance!");
Log("No fisher found for player instance!");
else
{
thisPlayer.InstanceID = actorID;
Expand Down Expand Up @@ -142,7 +144,7 @@ void OnNetworkPacket(byte[] packet, CSteamID sender)
if (serverInst.Type == "raincloud")
return;

Console.WriteLine($"Player asked to remove {serverInst.Type} actor");
Log($"Player asked to remove {serverInst.Type} actor");

// the sever owns the instance
removeServerActor(serverInst);
Expand All @@ -165,7 +167,7 @@ void OnNetworkPacket(byte[] packet, CSteamID sender)

if (canvas == null)
{
Console.WriteLine($"Creating new canvas: {canvasID}");
Log($"Creating new canvas: {canvasID}");
canvas = new Chalk.ChalkCanvas(canvasID);
chalkCanvas.Add(canvas);
}
Expand Down Expand Up @@ -215,7 +217,7 @@ internal void SendStagedChalkPackets(CSteamID recipient)
}
catch (Exception e)
{
Console.WriteLine(e);
Error(e.ToString());
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Cove/Server/Server.Utils.Networking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ partial class CoveServer
{
Dictionary<string, object> readPacket(byte[] packetBytes)
{
return (new GodotReader(packetBytes)).readPacket();
return (new GodotReader(packetBytes, logger)).readPacket();
}

byte[] writePacket(Dictionary<string, object> packet)
Expand Down
6 changes: 3 additions & 3 deletions Cove/Server/Server.Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void readAdmins()
{
if (config[key].ToLower() == "true")
{
Console.WriteLine($"Added {key} as admin!");
Log($"Added {key} as admin!");
Admins.Add(key);
WFPlayer player = AllPlayers.Find(p => p.SteamId.m_SteamID.ToString() == key);
if (player != null)
Expand Down Expand Up @@ -122,7 +122,7 @@ public WFActor spawnGenericActor(string type, Vector3 pos = null)
long IId = new Random().NextInt64();
while (findActorByID(IId) != null)
{
Console.WriteLine("Actor ID Collided!");
Log("Actor ID Collided!");
IId = new Random().NextInt64();
}

Expand Down Expand Up @@ -347,7 +347,7 @@ public void printPluginLog(string message, CovePlugin caller)
{

PluginInstance pluginInfo = loadedPlugins.Find(i => i.plugin == caller);
Console.WriteLine($"[{pluginInfo.pluginName}] {message}");
Log($"[{pluginInfo.pluginName}] {message}");
}
}
}
Loading

0 comments on commit 359b488

Please sign in to comment.