Skip to content

Commit

Permalink
0.3.1
Browse files Browse the repository at this point in the history
- Implement console logs
  • Loading branch information
xen-42 authored Dec 27, 2023
2 parents 4bfdf8b + 29dff11 commit 4dbe03a
Show file tree
Hide file tree
Showing 21 changed files with 472 additions and 57 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ jobs:
- name: Build Winch
run: dotnet build -c ${{ inputs.build_type }}

- name: Copy WinchConsole into Winch folder
run: |
cp -r WinchConsole/bin/* Winch/bin/
- name: Upload Winch Artifact
uses: actions/upload-artifact@v3
with:
Expand Down
12 changes: 12 additions & 0 deletions Winch.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DisasterButton", "Winch.Exa
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExampleItems", "Winch.Examples\ExampleItems\ExampleItems.csproj", "{C112288E-E993-44F3-B7B0-FB4BD37F18EA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinchConsole", "WinchConsole\WinchConsole.csproj", "{D5CFABA9-FA58-474F-A394-E197BDF38FDD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinchCommon", "WinchCommon\WinchCommon.csproj", "{EF5F69E6-FD4D-4314-B187-A89D00BF9355}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -33,6 +37,14 @@ Global
{C112288E-E993-44F3-B7B0-FB4BD37F18EA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C112288E-E993-44F3-B7B0-FB4BD37F18EA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C112288E-E993-44F3-B7B0-FB4BD37F18EA}.Release|Any CPU.Build.0 = Release|Any CPU
{D5CFABA9-FA58-474F-A394-E197BDF38FDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D5CFABA9-FA58-474F-A394-E197BDF38FDD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D5CFABA9-FA58-474F-A394-E197BDF38FDD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D5CFABA9-FA58-474F-A394-E197BDF38FDD}.Release|Any CPU.Build.0 = Release|Any CPU
{EF5F69E6-FD4D-4314-B187-A89D00BF9355}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF5F69E6-FD4D-4314-B187-A89D00BF9355}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF5F69E6-FD4D-4314-B187-A89D00BF9355}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF5F69E6-FD4D-4314-B187-A89D00BF9355}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
7 changes: 2 additions & 5 deletions Winch/Core/WinchCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,18 @@
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine.Profiling.Memory.Experimental;
using Winch.Config;
using Winch.Logging;
using Winch.Util;

namespace Winch.Core
{
public class WinchCore
public class WinchCore
{
public static Logger Log = new Logger();

public static Dictionary<string, object> WinchModConfig = new();

public static string WinchInstallLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
public static string WinchInstallLocation => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

public static void Main()
{
Expand Down
57 changes: 57 additions & 0 deletions Winch/Logging/LogSocket.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Winch.Logging
{
public class LogSocket
{
private Socket _socket;
private readonly int _port;
private readonly Logger _logger;

public LogSocket(Logger logger, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_port = port;
_logger = logger;
}

public void WriteToSocket(LogMessage logMessage)
{
if (_socket == null)
{
return;
}

if (!_socket.Connected)
{
var endPoint = new IPEndPoint(IPAddress.Parse(Constants.IP), _port);
try
{
_socket?.Connect(endPoint);
}
catch (Exception ex)
{
_socket = null;

Check warning on line 39 in Winch/Logging/LogSocket.cs

View workflow job for this annotation

GitHub Actions / Build / Create artifacts

Cannot convert null literal to non-nullable reference type.
_logger.Error($"Could not connect to console at {Constants.IP}:{_port} - {ex}");
}
}

try
{
_socket?.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(logMessage)));
}
catch (SocketException) { }
}

public void Close()
{
Thread.Sleep(TimeSpan.FromSeconds(1));
_socket?.Close();
}
}
}
91 changes: 67 additions & 24 deletions Winch/Logging/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,67 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using Winch.Config;
using Winch.Core;

namespace Winch.Logging
{
enum LogLevel
{
UNITY = 0, DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4
}

public class Logger
public class Logger
{
private LogFile? _log;
private LogFile? _latestLog;

private bool _writeLogs;
private bool _writeLogsToFile;
private bool _writeLogsToConsole;
private LogLevel? _minLogLevel;

public Logger()
{
_writeLogs = WinchConfig.GetProperty("WriteLogsToFile", true);
if (!_writeLogs)
return;
private LogSocket? _logSocket;

_minLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), WinchConfig.GetProperty("LogLevel", "DEBUG"));
_log = new LogFile();
_latestLog = new LogFile("latest.log");
public string LogConsoleExe => Path.Combine(WinchCore.WinchInstallLocation, "WinchConsole.exe");

CleanupLogs();
public Logger()
{
_writeLogsToFile = WinchConfig.GetProperty("WriteLogsToFile", true);
if (_writeLogsToFile)
{
_minLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), WinchConfig.GetProperty("LogLevel", "DEBUG"));
_log = new LogFile();
_latestLog = new LogFile("latest.log");
CleanupLogs();
}

_writeLogsToConsole = WinchConfig.GetProperty("WriteLogsToConsole", true);

if (_writeLogsToConsole)
{
// Find an avialable port for the logs
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();

// Console exe will get the port from the WinchConfig file
WinchConfig.SetProperty("LogPort", $"{port}");

Info($"Writing logs to port {port}");

try
{
Info($"Starting console at path {LogConsoleExe}");
Process.Start(LogConsoleExe);

_logSocket = new LogSocket(this, port);
}
catch (Exception e)
{
Error($"Could not start console : {e}");
}
}

Info($"Writing logs to file: {_writeLogsToFile}. Writing logs to console: {_writeLogsToConsole}.");
}

private static void CleanupLogs()
Expand Down Expand Up @@ -63,14 +95,25 @@ private void Log(LogLevel level, string message)

private void Log(LogLevel level, string message, string source)
{
if (!_writeLogs)
return;
if (level < _minLogLevel)
return;

string logMessage = $"[{GetLogTimestamp()}] [{source}] [{level}] : {message}";
_log?.Write(logMessage);
_latestLog?.Write(logMessage);
if (level < _minLogLevel)
return;

if (_writeLogsToConsole)
{
_logSocket?.WriteToSocket(new LogMessage()
{
Level = level,
Message = message,
Source = source
});
}

if (_writeLogsToFile)
{
string logMessage = $"[{GetLogTimestamp()}] [{source}] [{level}] : {message}";
_log?.Write(logMessage);
_latestLog?.Write(logMessage);
}
}

private string GetLogTimestamp()
Expand Down
20 changes: 5 additions & 15 deletions Winch/Winch.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,6 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>

<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>

<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>

<ItemGroup>
<None Include="mod_meta.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
Expand All @@ -49,4 +34,9 @@
<Copy SourceFiles="@(DLLs)" DestinationFolder="$(OutputPath)" />
</Target>

<ItemGroup>
<ProjectReference Include="..\WinchCommon\WinchCommon.csproj">
</ProjectReference>
</ItemGroup>

</Project>
3 changes: 2 additions & 1 deletion Winch/Winch.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<license type="expression">MIT</license>
</metadata>
<files>
<file src="bin\Winch.dll" target="lib\net48" />
<file src="bin\Release\Winch.dll" target="lib\net48" />
<file src="bin\Release\WinchCommon.dll" target="lib\net48" />
</files>
</package>
2 changes: 1 addition & 1 deletion Winch/mod_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"Name": "Winch",
"Author": "Hacktix",
"ModGUID": "hacktix.winch",
"Version": "0.3.0"
"Version": "0.3.1"
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"WriteLogsToFile": true,
"WriteLogsToConsole": false,
"LogLevel": "DEBUG",
"LogsFolder": "Logs",
"DetailedLogSources": false,
Expand Down
File renamed without changes.
9 changes: 3 additions & 6 deletions Winch/Config/ModConfig.cs → WinchCommon/Config/ModConfig.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Winch.Core;
using System.Reflection;

namespace Winch.Config
{
public class ModConfig : JSONConfig
public class ModConfig : JSONConfig
{
private static Dictionary<string, string> DefaultConfigs = new Dictionary<string, string>();
private static Dictionary<string, ModConfig> Instances = new Dictionary<string, ModConfig>();
Expand All @@ -18,7 +15,7 @@ private static string GetDefaultConfig(string modName)
{
if(!DefaultConfigs.ContainsKey(modName))
{
WinchCore.Log.Error($"No 'DefaultConfig' attribute found in mod_meta.json for {modName}!");
//WinchCore.Log.Error($"No 'DefaultConfig' attribute found in mod_meta.json for {modName}!");
throw new KeyNotFoundException($"No 'DefaultConfig' attribute found in mod_meta.json for {modName}!");
}
return DefaultConfigs[modName];
Expand Down
16 changes: 14 additions & 2 deletions Winch/Config/WinchConfig.cs → WinchCommon/Config/WinchConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class WinchConfig : JSONConfig
{
private static readonly string WinchConfigPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "WinchConfig.json");

private WinchConfig() : base(WinchConfigPath, Properties.Resources.DefaultConfig) { }
private WinchConfig() : base(WinchConfigPath, WinchCommon.Properties.Resources.DefaultConfig) { }

private static WinchConfig? _instance;
public static WinchConfig Instance
Expand All @@ -22,7 +22,19 @@ public static WinchConfig Instance

public static new T? GetProperty<T>(string key, T defaultValue)
{
return ((JSONConfig)Instance).GetProperty(key, defaultValue);
try
{
return ((JSONConfig)Instance).GetProperty(key, defaultValue);
}
catch
{
return defaultValue;
}
}

public static new void SetProperty<T>(string key, T value)
{
((JSONConfig)Instance).SetProperty(key, value);
}
}
}
12 changes: 12 additions & 0 deletions WinchCommon/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Winch;

public static class Constants
{
public const string IP = "127.0.0.1";
}
6 changes: 6 additions & 0 deletions WinchCommon/LogLevel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Winch;

public enum LogLevel
{
UNITY = 0, DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4
}
17 changes: 17 additions & 0 deletions WinchCommon/Logging/LogMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Newtonsoft.Json;
using WinchCommon;

namespace Winch.Logging
{
public class LogMessage
{
[JsonProperty("source")]
public string Source { get; set; }

Check warning on line 9 in WinchCommon/Logging/LogMessage.cs

View workflow job for this annotation

GitHub Actions / Build / Create artifacts

Non-nullable property 'Source' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

[JsonProperty("level")]
public LogLevel Level { get; set; }

[JsonProperty("message")]
public string Message { get; set; }

Check warning on line 15 in WinchCommon/Logging/LogMessage.cs

View workflow job for this annotation

GitHub Actions / Build / Create artifacts

Non-nullable property 'Message' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
}
}
Loading

0 comments on commit 4dbe03a

Please sign in to comment.