write individual server log files and main log file seperately

log writing is thread safe now
This commit is contained in:
RaidMax 2018-10-06 11:47:14 -05:00
parent c7547f1ad5
commit de902a58ac
17 changed files with 72 additions and 45 deletions

View File

@ -67,7 +67,7 @@ namespace IW4MAdmin.Application.Core
{ {
if (AuthenticatedClients.Values.Count > 18) if (AuthenticatedClients.Values.Count > 18)
{ {
Program.ServerManager.GetLogger().WriteWarning($"auth client count is {AuthenticatedClients.Values.Count}, this is bad"); Program.ServerManager.GetLogger(0).WriteError($"auth client count is {AuthenticatedClients.Values.Count}, this is bad");
return AuthenticatedClients.Values.Take(18).ToList(); return AuthenticatedClients.Values.Take(18).ToList();
} }

View File

@ -55,9 +55,9 @@ namespace IW4MAdmin.Application.IO
catch (Exception e) catch (Exception e)
{ {
Program.ServerManager.GetLogger().WriteWarning("Could not properly parse event line"); server.Logger.WriteWarning("Could not properly parse event line");
Program.ServerManager.GetLogger().WriteDebug(e.Message); server.Logger.WriteDebug(e.Message);
Program.ServerManager.GetLogger().WriteDebug(eventLine); server.Logger.WriteDebug(eventLine);
} }
} }
} }

View File

@ -59,9 +59,9 @@ namespace IW4MAdmin.Application.IO
catch (Exception e) catch (Exception e)
{ {
Program.ServerManager.GetLogger().WriteWarning("Could not properly parse event line"); server.Logger.WriteWarning("Could not properly parse event line");
Program.ServerManager.GetLogger().WriteDebug(e.Message); server.Logger.WriteDebug(e.Message);
Program.ServerManager.GetLogger().WriteDebug(eventLine); server.Logger.WriteDebug(eventLine);
} }
} }
} }

View File

@ -59,7 +59,7 @@ namespace IW4MAdmin.Application.Localization
{ {
if (!localizationDict.TryAdd(item.Key, item.Value)) if (!localizationDict.TryAdd(item.Key, item.Value))
{ {
Program.ServerManager.GetLogger().WriteError($"Could not add locale string {item.Key} to localization"); Program.ServerManager.GetLogger(0).WriteError($"Could not add locale string {item.Key} to localization");
} }
} }
} }

View File

@ -2,6 +2,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Threading;
namespace IW4MAdmin.Application namespace IW4MAdmin.Application
{ {
@ -18,18 +19,18 @@ namespace IW4MAdmin.Application
} }
readonly string FileName; readonly string FileName;
readonly object ThreadLock; readonly SemaphoreSlim OnLogWriting;
public Logger(string fn) public Logger(string fn)
{ {
FileName = Path.Join("Log", fn); FileName = Path.Join("Log", $"{fn}-{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.log");
ThreadLock = new object(); OnLogWriting = new SemaphoreSlim(1,1);
if (File.Exists(fn))
File.Delete(fn);
} }
void Write(string msg, LogType type) void Write(string msg, LogType type)
{ {
OnLogWriting.Wait();
string stringType = type.ToString(); string stringType = type.ToString();
try try
@ -40,8 +41,6 @@ namespace IW4MAdmin.Application
catch (Exception) { } catch (Exception) { }
string LogLine = $"[{DateTime.Now.ToString("MM.dd.yyy HH:mm:ss.fff")}] - {stringType}: {msg}"; string LogLine = $"[{DateTime.Now.ToString("MM.dd.yyy HH:mm:ss.fff")}] - {stringType}: {msg}";
lock (ThreadLock)
{
#if DEBUG #if DEBUG
// lets keep it simple and dispose of everything quickly as logging wont be that much (relatively) // lets keep it simple and dispose of everything quickly as logging wont be that much (relatively)
@ -53,7 +52,8 @@ namespace IW4MAdmin.Application
//if (type != LogType.Debug) //if (type != LogType.Debug)
File.AppendAllText(FileName, $"{LogLine}{Environment.NewLine}"); File.AppendAllText(FileName, $"{LogLine}{Environment.NewLine}");
#endif #endif
}
OnLogWriting.Release(1);
} }
public void WriteVerbose(string msg) public void WriteVerbose(string msg)

View File

@ -27,7 +27,7 @@ namespace IW4MAdmin.Application
private List<Server> _servers; private List<Server> _servers;
public List<Server> Servers => _servers.OrderByDescending(s => s.ClientNum).ToList(); public List<Server> Servers => _servers.OrderByDescending(s => s.ClientNum).ToList();
public Dictionary<int, Player> PrivilegedClients { get; set; } public Dictionary<int, Player> PrivilegedClients { get; set; }
public ILogger Logger { get; private set; } public ILogger Logger => GetLogger(0);
public bool Running { get; private set; } public bool Running { get; private set; }
public bool IsInitialized { get; private set; } public bool IsInitialized { get; private set; }
// define what the delagate function looks like // define what the delagate function looks like
@ -49,11 +49,12 @@ namespace IW4MAdmin.Application
ManualResetEventSlim OnQuit; ManualResetEventSlim OnQuit;
readonly IPageList PageList; readonly IPageList PageList;
readonly SemaphoreSlim ProcessingEvent = new SemaphoreSlim(1, 1); readonly SemaphoreSlim ProcessingEvent = new SemaphoreSlim(1, 1);
readonly Dictionary<int, ILogger> Loggers = new Dictionary<int, ILogger>();
private ApplicationManager() private ApplicationManager()
{ {
Logger = new Logger("IW4MAdmin.log");
// do any needed migrations // do any needed migrations
// todo: move out
ConfigurationMigration.MoveConfigFolder10518(Logger); ConfigurationMigration.MoveConfigFolder10518(Logger);
_servers = new List<Server>(); _servers = new List<Server>();
Commands = new List<Command>(); Commands = new List<Command>();
@ -568,9 +569,29 @@ namespace IW4MAdmin.Application
Running = false; Running = false;
} }
public ILogger GetLogger() public ILogger GetLogger(int serverId)
{ {
return Logger; if (Loggers.ContainsKey(serverId))
{
return Loggers[serverId];
}
else
{
Logger newLogger;
if (serverId == 0)
{
newLogger = new Logger("IW4MAdmin-Manager");
}
else
{
newLogger = new Logger($"IW4MAdmin-Server-{serverId}");
}
Loggers.Add(serverId, newLogger);
return newLogger;
}
} }
public IList<MessageToken> GetMessageTokens() public IList<MessageToken> GetMessageTokens()

View File

@ -47,6 +47,13 @@ namespace IW4MAdmin.Application.Migration
File.Move(configFile, destinationPath); File.Move(configFile, destinationPath);
} }
} }
if (!File.Exists(Path.Join("Database", "Database.db")) &&
File.Exists("Database.db"))
{
log.WriteDebug("Moving database file");
File.Move("Database.db", Path.Join("Database", "Database.db"));
}
} }
} }
} }

View File

@ -201,7 +201,7 @@ namespace IW4MAdmin
{ {
player.Level = Player.Permission.User; player.Level = Player.Permission.User;
} }
#if DEBUG == false
if (currentBan != null) if (currentBan != null)
{ {
Logger.WriteInfo($"Banned client {player} trying to connect..."); Logger.WriteInfo($"Banned client {player} trying to connect...");
@ -243,7 +243,6 @@ namespace IW4MAdmin
Players[player.ClientNumber] = null; Players[player.ClientNumber] = null;
return false; return false;
} }
#endif
player.State = Player.ClientState.Connected; player.State = Player.ClientState.Connected;
return true; return true;
@ -251,9 +250,9 @@ namespace IW4MAdmin
catch (Exception ex) catch (Exception ex)
{ {
Manager.GetLogger().WriteError($"{loc["SERVER_ERROR_ADDPLAYER"]} {polledPlayer.Name}::{polledPlayer.NetworkId}"); Logger.WriteError($"{loc["SERVER_ERROR_ADDPLAYER"]} {polledPlayer.Name}::{polledPlayer.NetworkId}");
Manager.GetLogger().WriteDebug(ex.Message); Logger.WriteDebug(ex.Message);
Manager.GetLogger().WriteDebug(ex.StackTrace); Logger.WriteDebug(ex.StackTrace);
return false; return false;
} }
} }
@ -335,7 +334,7 @@ namespace IW4MAdmin
(canExecuteCommand || (canExecuteCommand ||
E.Origin?.Level == Player.Permission.Console)) E.Origin?.Level == Player.Permission.Console))
{ {
var _ = (((Command)E.Extra).ExecuteAsync(E)); await (((Command)E.Extra).ExecuteAsync(E));
} }
} }

View File

@ -35,7 +35,7 @@ namespace IW4MAdmin.Plugins.Stats.Helpers
{ {
Servers = new ConcurrentDictionary<int, ServerStats>(); Servers = new ConcurrentDictionary<int, ServerStats>();
ContextThreads = new ConcurrentDictionary<int, ThreadSafeStatsService>(); ContextThreads = new ConcurrentDictionary<int, ThreadSafeStatsService>();
Log = mgr.GetLogger(); Log = mgr.GetLogger(0);
Manager = mgr; Manager = mgr;
OnProcessingPenalty = new SemaphoreSlim(1, 1); OnProcessingPenalty = new SemaphoreSlim(1, 1);
} }

View File

@ -108,7 +108,7 @@ namespace IW4MAdmin.Plugins.Welcome
catch (Exception) catch (Exception)
{ {
joining.CurrentServer.Manager.GetLogger().WriteError("Could not open file Plugins\\GeoIP.dat for Welcome Plugin"); joining.CurrentServer.Logger.WriteError("Could not open file Plugins\\GeoIP.dat for Welcome Plugin");
} }
msg = msg.Replace("{{TimesConnected}}", TimesConnected(joining)); msg = msg.Replace("{{TimesConnected}}", TimesConnected(joining));

View File

@ -1126,7 +1126,7 @@ namespace SharedLibraryCore.Commands
{ {
} }
public override async Task ExecuteAsync(GameEvent E) public override Task ExecuteAsync(GameEvent E)
{ {
var gameserverProcesses = System.Diagnostics.Process.GetProcessesByName("iw4x"); var gameserverProcesses = System.Diagnostics.Process.GetProcessesByName("iw4x");
@ -1180,10 +1180,12 @@ namespace SharedLibraryCore.Commands
E.Origin.Tell("Could not kill server process"); E.Origin.Tell("Could not kill server process");
E.Owner.Logger.WriteDebug("Unable to kill process"); E.Owner.Logger.WriteDebug("Unable to kill process");
E.Owner.Logger.WriteDebug($"Exception: {e.Message}"); E.Owner.Logger.WriteDebug($"Exception: {e.Message}");
return; return Task.CompletedTask;
} }
} }
} }
return Task.CompletedTask;
} }
} }

View File

@ -13,7 +13,7 @@ namespace SharedLibraryCore.Interfaces
Task Init(); Task Init();
void Start(); void Start();
void Stop(); void Stop();
ILogger GetLogger(); ILogger GetLogger(int serverId);
IList<Server> GetServers(); IList<Server> GetServers();
IList<Command> GetCommands(); IList<Command> GetCommands();
IList<Helpers.MessageToken> GetMessageTokens(); IList<Helpers.MessageToken> GetMessageTokens();

View File

@ -339,7 +339,6 @@ namespace SharedLibraryCore.Objects
if (sender.Level <= this.Level) if (sender.Level <= this.Level)
{ {
e.FailReason = GameEvent.EventFailReason.Permission; e.FailReason = GameEvent.EventFailReason.Permission;
return e;
} }
sender.CurrentServer.Manager.GetEventHandler().AddEvent(e); sender.CurrentServer.Manager.GetEventHandler().AddEvent(e);
@ -367,7 +366,6 @@ namespace SharedLibraryCore.Objects
if (sender.Level <= this.Level) if (sender.Level <= this.Level)
{ {
e.FailReason = GameEvent.EventFailReason.Permission; e.FailReason = GameEvent.EventFailReason.Permission;
return e;
} }
sender.CurrentServer.Manager.GetEventHandler().AddEvent(e); sender.CurrentServer.Manager.GetEventHandler().AddEvent(e);

View File

@ -34,7 +34,7 @@ namespace SharedLibraryCore.Plugins
if (dllFileNames.Length == 0 && if (dllFileNames.Length == 0 &&
scriptFileNames.Length == 0) scriptFileNames.Length == 0)
{ {
Manager.GetLogger().WriteDebug(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_NOTFOUND"]); Manager.GetLogger(0).WriteDebug(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_NOTFOUND"]);
return true; return true;
} }
@ -43,7 +43,7 @@ namespace SharedLibraryCore.Plugins
{ {
var plugin = new ScriptPlugin(fileName); var plugin = new ScriptPlugin(fileName);
plugin.Initialize(Manager).Wait(); plugin.Initialize(Manager).Wait();
Manager.GetLogger().WriteDebug($"Loaded script plugin \"{ plugin.Name }\" [{plugin.Version}]"); Manager.GetLogger(0).WriteDebug($"Loaded script plugin \"{ plugin.Name }\" [{plugin.Version}]");
ActivePlugins.Add(plugin); ActivePlugins.Add(plugin);
} }
@ -66,7 +66,7 @@ namespace SharedLibraryCore.Plugins
Object commandObject = Activator.CreateInstance(assemblyType); Object commandObject = Activator.CreateInstance(assemblyType);
Command newCommand = (Command)commandObject; Command newCommand = (Command)commandObject;
ActiveCommands.Add(newCommand); ActiveCommands.Add(newCommand);
Manager.GetLogger().WriteDebug($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_REGISTERCMD"]} \"{newCommand.Name}\""); Manager.GetLogger(0).WriteDebug($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_REGISTERCMD"]} \"{newCommand.Name}\"");
LoadedCommands++; LoadedCommands++;
continue; continue;
} }
@ -82,18 +82,18 @@ namespace SharedLibraryCore.Plugins
{ {
ActivePlugins.Add(newNotify); ActivePlugins.Add(newNotify);
PluginAssemblies.Add(Plugin); PluginAssemblies.Add(Plugin);
Manager.GetLogger().WriteDebug($"Loaded plugin \"{ newNotify.Name }\" [{newNotify.Version}]"); Manager.GetLogger(0).WriteDebug($"Loaded plugin \"{ newNotify.Name }\" [{newNotify.Version}]");
} }
} }
catch (Exception E) catch (Exception E)
{ {
Manager.GetLogger().WriteWarning($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"]} {Plugin.Location} - {E.Message}"); Manager.GetLogger(0).WriteWarning($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"]} {Plugin.Location} - {E.Message}");
} }
} }
} }
} }
Manager.GetLogger().WriteInfo($"Loaded {ActivePlugins.Count} plugins and registered {LoadedCommands} commands."); Manager.GetLogger(0).WriteInfo($"Loaded {ActivePlugins.Count} plugins and registered {LoadedCommands} commands.");
return true; return true;
} }
} }

View File

@ -42,8 +42,8 @@ namespace SharedLibraryCore
} }
catch (Exception ex) catch (Exception ex)
{ {
Manager.GetLogger().WriteError($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"]} {Name}"); Manager.GetLogger(0).WriteError($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"]} {Name}");
Manager.GetLogger().WriteDebug(ex.Message); Manager.GetLogger(0).WriteDebug(ex.Message);
} }
} }

View File

@ -32,7 +32,7 @@ namespace SharedLibraryCore
IP = config.IPAddress; IP = config.IPAddress;
Port = config.Port; Port = config.Port;
Manager = mgr; Manager = mgr;
Logger = Manager.GetLogger(); Logger = Manager.GetLogger(this.GetHashCode());
ServerConfig = config; ServerConfig = config;
RemoteConnection = new RCon.Connection(IP, Port, Password, Logger); RemoteConnection = new RCon.Connection(IP, Port, Password, Logger);

View File

@ -23,9 +23,9 @@ namespace WebfrontCore.Controllers
public IActionResult Error() public IActionResult Error()
{ {
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>(); var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
Manager.GetLogger().WriteError($"[Webfront] {exceptionFeature.Error.Message}"); Manager.GetLogger(0).WriteError($"[Webfront] {exceptionFeature.Error.Message}");
Manager.GetLogger().WriteDebug(exceptionFeature.Path); Manager.GetLogger(0).WriteDebug(exceptionFeature.Path);
Manager.GetLogger().WriteDebug(exceptionFeature.Error.StackTrace); Manager.GetLogger(0).WriteDebug(exceptionFeature.Error.StackTrace);
ViewBag.Description = Localization["WEBFRONT_ERROR_DESC"]; ViewBag.Description = Localization["WEBFRONT_ERROR_DESC"];
ViewBag.Title = Localization["WEBFRONT_ERROR_TITLE"]; ViewBag.Title = Localization["WEBFRONT_ERROR_TITLE"];