Added first simple logger for CoopClient

This commit is contained in:
EntenKoeniq
2022-03-28 23:59:19 +02:00
parent 98a593daae
commit 90d7ae7059
3 changed files with 74 additions and 2 deletions

View File

@ -92,6 +92,7 @@
<Compile Include="Entities\Player\Sync\OnFootSync.cs" />
<Compile Include="Entities\Player\Sync\VehicleSync.cs" />
<Compile Include="JavascriptHook.cs" />
<Compile Include="Logger.cs" />
<Compile Include="Main.cs" />
<Compile Include="Menus\MenusMain.cs" />
<Compile Include="Menus\Sub\Servers.cs" />

View File

@ -50,7 +50,7 @@ namespace CoopClient
}
catch (Exception ex)
{
// TODO
Logger.Write(ex.Message, Logger.LogLevel.Server);
}
}
@ -70,7 +70,7 @@ namespace CoopClient
}
catch (Exception ex)
{
// TODO
Logger.Write(ex.Message, Logger.LogLevel.Server);
}
finally
{

71
Client/Logger.cs Normal file
View File

@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Linq;
namespace CoopClient
{
internal static class Logger
{
public enum LogLevel
{
Normal,
Server,
Custom
}
public static void Write(string message, LogLevel level = LogLevel.Normal, string filepath = null)
{
string newFilePath = null;
switch (level)
{
case LogLevel.Normal:
newFilePath = "scripts\\CoopLog.txt";
break;
case LogLevel.Server:
newFilePath = $"scripts\\resources\\{Main.MainSettings.LastServerAddress.Replace(":", ".")}\\CoopLog.txt";
break;
case LogLevel.Custom:
if (string.IsNullOrEmpty(filepath))
{
goto case LogLevel.Normal;
}
newFilePath = filepath;
break;
}
try
{
if (File.Exists(newFilePath))
{
// Check if the rows are under 20 and delete the first 10 if so to avoid large logs
// Firstly get all lines
string[] oldLines = File.ReadAllLines(newFilePath);
// Check the length of the lines
if (oldLines.Length >= 20)
{
// Now overwrite the file without the first 10 lines
File.WriteAllLines(newFilePath, oldLines.Skip(10).ToArray());
}
}
using (StreamWriter sw = new StreamWriter(newFilePath, true))
{
Log(message, sw);
sw.Flush();
sw.Close();
}
}
catch
{ }
}
private static void Log(string message, TextWriter writer)
{
writer.WriteLine($"[{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}] : {message}");
}
}
}