Skip to content

Commit

Permalink
Log error fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
zabszk committed Jan 2, 2021
1 parent cf08202 commit f2c0e83
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 45 deletions.
83 changes: 42 additions & 41 deletions Core/LocalAdmin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,26 @@ namespace LocalAdmin.V2.Core

public sealed class LocalAdmin : IDisposable
{
public const string VersionString = "2.3.2";
public const string VersionString = "2.3.3";
public static LocalAdmin? Singleton;
public static ushort GamePort;
private static bool _firstRun = true;

private readonly CommandService commandService = new CommandService();
private Process? gameProcess;
private readonly CommandService _commandService = new CommandService();
private Process? _gameProcess;
internal TcpServer? Server { get; private set; }
private Task? readerTask;
private readonly string scpslExecutable;
private Task? _readerTask;
private readonly string _scpslExecutable;
private static string _gameArguments = string.Empty;
internal static string BaseWindowTitle = $"LocalAdmin v. {VersionString}";
internal static readonly string GameUserDataRoot =
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar +
"SCP Secret Laboratory" + Path.DirectorySeparatorChar;
private static bool _exit;
private static readonly ConcurrentQueue<string> InputQueue = new ConcurrentQueue<string>();
internal static bool NoSetCursor, PrintControlMessages, StdPrint, AutoFlush = true, EnableLogging = true;
private volatile bool processClosing;
internal static bool NoSetCursor, PrintControlMessages, AutoFlush = true, EnableLogging = true;
private static bool _stdPrint;
private volatile bool _processClosing;

internal static Config? Configuration;

Expand All @@ -64,14 +65,14 @@ internal enum ShutdownAction : byte
internal LocalAdmin()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
scpslExecutable = "SCPSL.exe";
_scpslExecutable = "SCPSL.exe";
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
scpslExecutable = "SCPSL.x86_64";
_scpslExecutable = "SCPSL.x86_64";
else
{
ConsoleUtil.WriteLine("Failed - Unsupported platform!", ConsoleColor.Red);
// shut up dotnet
scpslExecutable = "";
_scpslExecutable = string.Empty;
Exit(1);
}
}
Expand Down Expand Up @@ -147,7 +148,7 @@ public void Start(string[] args)
break;

case 's':
StdPrint = true;
_stdPrint = true;
break;
}
}
Expand Down Expand Up @@ -176,7 +177,7 @@ public void Start(string[] args)
break;

case "--printStd":
StdPrint = true;
_stdPrint = true;
break;

case "--":
Expand Down Expand Up @@ -235,7 +236,7 @@ public void Start(string[] args)

StartSession();

readerTask!.Start();
_readerTask!.Start();

if (!EnableLogging)
ConsoleUtil.WriteLine("Logging has been disabled.", ConsoleColor.Red);
Expand Down Expand Up @@ -276,7 +277,7 @@ public void Start(string[] args)
private void StartSession()
{
// Terminate the game, if the game process is exists
if (gameProcess != null && !gameProcess.HasExited)
if (_gameProcess != null && !_gameProcess.HasExited)
TerminateGame();

Menu();
Expand Down Expand Up @@ -393,7 +394,7 @@ private void SetupKeyboardInput()

private void SetupReader()
{
readerTask = new Task(async () =>
_readerTask = new Task(async () =>
{
while (Server == null)
await Task.Delay(20);
Expand Down Expand Up @@ -421,7 +422,7 @@ private void SetupReader()
else
ConsoleUtil.WriteLine($">>> {input}", ConsoleColor.DarkMagenta, -1);

if (gameProcess != null && gameProcess.HasExited)
if (_gameProcess != null && _gameProcess.HasExited)
{
ConsoleUtil.WriteLine("Failed to send command - the game process was terminated...",
ConsoleColor.Red);
Expand All @@ -435,7 +436,7 @@ private void SetupReader()
continue;
var name = split[0].ToUpperInvariant();

var command = commandService.GetCommandByName(name);
var command = _commandService.GetCommandByName(name);

if (command != null)
{
Expand Down Expand Up @@ -467,46 +468,46 @@ private void SetupReader()

private void RunScpsl()
{
if (File.Exists(scpslExecutable))
if (File.Exists(_scpslExecutable))
{
ConsoleUtil.WriteLine("Executing: " + scpslExecutable, ConsoleColor.DarkGreen);
ConsoleUtil.WriteLine("Executing: " + _scpslExecutable, ConsoleColor.DarkGreen);
var redirectStreams = Configuration!.LaShowStdoutStderr || Configuration!.LaLogStdoutStderr;

var startInfo = new ProcessStartInfo
{
FileName = scpslExecutable,
FileName = _scpslExecutable,
Arguments = $"-batchmode -nographics -nodedicateddelete -port{GamePort} -console{Server!.ConsolePort} -id{Environment.ProcessId} {_gameArguments}",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = redirectStreams,
RedirectStandardError = redirectStreams,
};

gameProcess = Process.Start(startInfo);
_gameProcess = Process.Start(startInfo);

if (!redirectStreams) return;
gameProcess!.OutputDataReceived += (sender, args) =>
_gameProcess!.OutputDataReceived += (sender, args) =>
{
if (string.IsNullOrWhiteSpace(args.Data))
return;

ConsoleUtil.WriteLine("[STDOUT] " + args.Data, ConsoleColor.Gray, log: Configuration!.LaLogStdoutStderr || StdPrint, display: Configuration!.LaShowStdoutStderr);
ConsoleUtil.WriteLine("[STDOUT] " + args.Data, ConsoleColor.Gray, log: Configuration!.LaLogStdoutStderr || _stdPrint, display: Configuration!.LaShowStdoutStderr);
};

gameProcess!.ErrorDataReceived += (sender, args) =>
_gameProcess!.ErrorDataReceived += (sender, args) =>
{
if (string.IsNullOrWhiteSpace(args.Data))
return;

ConsoleUtil.WriteLine("[STDERR] " + args.Data, ConsoleColor.DarkMagenta, log: Configuration!.LaLogStdoutStderr || StdPrint, display: Configuration!.LaShowStdoutStderr);
ConsoleUtil.WriteLine("[STDERR] " + args.Data, ConsoleColor.DarkMagenta, log: Configuration!.LaLogStdoutStderr || _stdPrint, display: Configuration!.LaShowStdoutStderr);
};

gameProcess!.BeginOutputReadLine();
gameProcess!.BeginErrorReadLine();
_gameProcess!.BeginOutputReadLine();
_gameProcess!.BeginErrorReadLine();

gameProcess!.Exited += (sender, args) =>
_gameProcess!.Exited += (sender, args) =>
{
if (processClosing)
if (_processClosing)
return;

switch (ExitAction)
Expand All @@ -533,7 +534,7 @@ private void RunScpsl()
}
};

gameProcess!.EnableRaisingEvents = true;
_gameProcess!.EnableRaisingEvents = true;
}
else
{
Expand All @@ -549,10 +550,10 @@ private void RunScpsl()

private void RegisterCommands()
{
commandService.RegisterCommand(new RestartCommand());
commandService.RegisterCommand(new ForceRestartCommand());
commandService.RegisterCommand(new HelpCommand());
commandService.RegisterCommand(new LicenseCommand());
_commandService.RegisterCommand(new RestartCommand());
_commandService.RegisterCommand(new ForceRestartCommand());
_commandService.RegisterCommand(new HelpCommand());
_commandService.RegisterCommand(new LicenseCommand());
}

private static void ReadInput(Func<string?, bool> checkInput, Action validInputAction, Action invalidInputAction)
Expand All @@ -575,8 +576,8 @@ private static void ReadInput(Func<string?, bool> checkInput, Action validInputA
private void TerminateGame()
{
Server?.Stop();
if (gameProcess != null && !gameProcess.HasExited)
gameProcess.Kill();
if (_gameProcess != null && !_gameProcess.HasExited)
_gameProcess.Kill();
}

/// <summary>
Expand All @@ -586,20 +587,20 @@ public void Exit(int code = -1, bool waitForKey = false, bool restart = false)
{
lock (this)
{
if (processClosing)
if (_processClosing)
return;

_exit = true;
processClosing = true;
_processClosing = true;
LogCleaner.Abort();
Logger.EndLogging();
TerminateGame(); // Forcefully terminating the process
gameProcess?.Dispose();
_gameProcess?.Dispose();

try
{
if (readerTask != null && readerTask.IsCompleted)
readerTask?.Dispose();
if (_readerTask != null && _readerTask.IsCompleted)
_readerTask?.Dispose();
}
catch
{
Expand Down
38 changes: 34 additions & 4 deletions IO/Logging/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace LocalAdmin.V2.IO.Logging
public static class Logger
{
private static StreamWriter? _sw;
private static string? _logPath;
internal const string LogFolderName = "LocalAdminLogs";

public static void Initialize()
Expand All @@ -19,8 +20,8 @@ public static void Initialize()
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

_sw = new StreamWriter(dir +
$"LocalAdmin Log {DateTime.Now:yyyy-MM-dd HH.mm.ss}.txt") {AutoFlush = Core.LocalAdmin.AutoFlush};
_logPath = dir + $"LocalAdmin Log {DateTime.Now:yyyy-MM-dd HH.mm.ss}.txt";
_sw = new StreamWriter(_logPath) {AutoFlush = Core.LocalAdmin.AutoFlush};

Log($"{ConsoleUtil.GetTimestamp()} Logging started.");
}
Expand All @@ -34,9 +35,38 @@ public static void EndLogging()
_sw.Dispose();
_sw = null;
}

private static void AppendLog(string text)
{
if (_sw == null) return;

try
{
if (_sw.BaseStream.CanWrite) _sw.WriteLine(text);
else
{
try
{
_sw.Close();
}
catch
{
//Ignore
}

_sw = File.AppendText(_logPath!);
_sw.AutoFlush = Core.LocalAdmin.AutoFlush;
_sw.WriteLine(text);
}
}
catch (Exception e)
{
Console.Write("Failed to write log: " + e.Message);
}
}

public static void Log(string text) => _sw?.WriteLine(text);
public static void Log(string text) => AppendLog(text);

public static void Log(object obj) => _sw?.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff zzz}] {obj}");
public static void Log(object obj) => AppendLog($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff zzz}] {obj}");
}
}

0 comments on commit f2c0e83

Please sign in to comment.