Skip to content

Commit

Permalink
write individual server log files and main log file seperately
Browse files Browse the repository at this point in the history
log writing is thread safe now
  • Loading branch information
RaidMax committed Oct 6, 2018
1 parent ac85429 commit b902069
Show file tree
Hide file tree
Showing 17 changed files with 72 additions and 45 deletions.
2 changes: 1 addition & 1 deletion Application/Core/ClientAuthentication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public IList<Player> GetAuthenticatedClients()
{
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();
}

Expand Down
6 changes: 3 additions & 3 deletions Application/IO/GameLogReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ public ICollection<GameEvent> ReadEventsFromLog(Server server, long fileSizeDiff

catch (Exception e)
{
Program.ServerManager.GetLogger().WriteWarning("Could not properly parse event line");
Program.ServerManager.GetLogger().WriteDebug(e.Message);
Program.ServerManager.GetLogger().WriteDebug(eventLine);
server.Logger.WriteWarning("Could not properly parse event line");
server.Logger.WriteDebug(e.Message);
server.Logger.WriteDebug(eventLine);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions Application/IO/GameLogReaderHttp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ public ICollection<GameEvent> ReadEventsFromLog(Server server, long fileSizeDiff

catch (Exception e)
{
Program.ServerManager.GetLogger().WriteWarning("Could not properly parse event line");
Program.ServerManager.GetLogger().WriteDebug(e.Message);
Program.ServerManager.GetLogger().WriteDebug(eventLine);
server.Logger.WriteWarning("Could not properly parse event line");
server.Logger.WriteDebug(e.Message);
server.Logger.WriteDebug(eventLine);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Application/Localization/Configure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static void Initialize(string customLocale)
{
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");
}
}
}
Expand Down
16 changes: 8 additions & 8 deletions Application/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace IW4MAdmin.Application
{
Expand All @@ -18,18 +19,18 @@ enum LogType
}

readonly string FileName;
readonly object ThreadLock;
readonly SemaphoreSlim OnLogWriting;

public Logger(string fn)
{
FileName = Path.Join("Log", fn);
ThreadLock = new object();
if (File.Exists(fn))
File.Delete(fn);
FileName = Path.Join("Log", $"{fn}-{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.log");
OnLogWriting = new SemaphoreSlim(1,1);
}

void Write(string msg, LogType type)
{
OnLogWriting.Wait();

string stringType = type.ToString();

try
Expand All @@ -40,8 +41,6 @@ void Write(string msg, LogType type)
catch (Exception) { }

string LogLine = $"[{DateTime.Now.ToString("MM.dd.yyy HH:mm:ss.fff")}] - {stringType}: {msg}";
lock (ThreadLock)
{
#if DEBUG
// lets keep it simple and dispose of everything quickly as logging wont be that much (relatively)

Expand All @@ -53,7 +52,8 @@ void Write(string msg, LogType type)
//if (type != LogType.Debug)
File.AppendAllText(FileName, $"{LogLine}{Environment.NewLine}");
#endif
}

OnLogWriting.Release(1);
}

public void WriteVerbose(string msg)
Expand Down
29 changes: 25 additions & 4 deletions Application/Manager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class ApplicationManager : IManager
private List<Server> _servers;
public List<Server> Servers => _servers.OrderByDescending(s => s.ClientNum).ToList();
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 IsInitialized { get; private set; }
// define what the delagate function looks like
Expand All @@ -49,11 +49,12 @@ public class ApplicationManager : IManager
ManualResetEventSlim OnQuit;
readonly IPageList PageList;
readonly SemaphoreSlim ProcessingEvent = new SemaphoreSlim(1, 1);
readonly Dictionary<int, ILogger> Loggers = new Dictionary<int, ILogger>();

private ApplicationManager()
{
Logger = new Logger("IW4MAdmin.log");
// do any needed migrations
// todo: move out
ConfigurationMigration.MoveConfigFolder10518(Logger);
_servers = new List<Server>();
Commands = new List<Command>();
Expand Down Expand Up @@ -568,9 +569,29 @@ public void Stop()
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()
Expand Down
7 changes: 7 additions & 0 deletions Application/Migration/ConfigurationMigration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ public static void MoveConfigFolder10518(ILogger log)
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"));
}
}
}
}
Expand Down
11 changes: 5 additions & 6 deletions Application/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ override public async Task<bool> AddPlayer(Player polledPlayer)
{
player.Level = Player.Permission.User;
}
#if DEBUG == false

if (currentBan != null)
{
Logger.WriteInfo($"Banned client {player} trying to connect...");
Expand Down Expand Up @@ -243,17 +243,16 @@ override public async Task<bool> AddPlayer(Player polledPlayer)
Players[player.ClientNumber] = null;
return false;
}
#endif

player.State = Player.ClientState.Connected;
return true;
}

catch (Exception ex)
{
Manager.GetLogger().WriteError($"{loc["SERVER_ERROR_ADDPLAYER"]} {polledPlayer.Name}::{polledPlayer.NetworkId}");
Manager.GetLogger().WriteDebug(ex.Message);
Manager.GetLogger().WriteDebug(ex.StackTrace);
Logger.WriteError($"{loc["SERVER_ERROR_ADDPLAYER"]} {polledPlayer.Name}::{polledPlayer.NetworkId}");
Logger.WriteDebug(ex.Message);
Logger.WriteDebug(ex.StackTrace);
return false;
}
}
Expand Down Expand Up @@ -335,7 +334,7 @@ public override async Task ExecuteEvent(GameEvent E)
(canExecuteCommand ||
E.Origin?.Level == Player.Permission.Console))
{
var _ = (((Command)E.Extra).ExecuteAsync(E));
await (((Command)E.Extra).ExecuteAsync(E));
}
}

Expand Down
2 changes: 1 addition & 1 deletion Plugins/Stats/Helpers/StatManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public StatManager(IManager mgr)
{
Servers = new ConcurrentDictionary<int, ServerStats>();
ContextThreads = new ConcurrentDictionary<int, ThreadSafeStatsService>();
Log = mgr.GetLogger();
Log = mgr.GetLogger(0);
Manager = mgr;
OnProcessingPenalty = new SemaphoreSlim(1, 1);
}
Expand Down
2 changes: 1 addition & 1 deletion Plugins/Welcome/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private string ProcessAnnouncement(string msg, Player joining)

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));

Expand Down
6 changes: 4 additions & 2 deletions SharedLibraryCore/Commands/NativeCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,7 @@ public CKillServer() : base("killserver", "kill the game server", "kill", Player
{
}

public override async Task ExecuteAsync(GameEvent E)
public override Task ExecuteAsync(GameEvent E)
{
var gameserverProcesses = System.Diagnostics.Process.GetProcessesByName("iw4x");

Expand Down Expand Up @@ -1180,10 +1180,12 @@ public override async Task ExecuteAsync(GameEvent E)
E.Origin.Tell("Could not kill server process");
E.Owner.Logger.WriteDebug("Unable to kill process");
E.Owner.Logger.WriteDebug($"Exception: {e.Message}");
return;
return Task.CompletedTask;
}
}
}

return Task.CompletedTask;
}
}

Expand Down
2 changes: 1 addition & 1 deletion SharedLibraryCore/Interfaces/IManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public interface IManager
Task Init();
void Start();
void Stop();
ILogger GetLogger();
ILogger GetLogger(int serverId);
IList<Server> GetServers();
IList<Command> GetCommands();
IList<Helpers.MessageToken> GetMessageTokens();
Expand Down
2 changes: 0 additions & 2 deletions SharedLibraryCore/Objects/Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,6 @@ public GameEvent TempBan(String tempbanReason, TimeSpan banLength, Player sender
if (sender.Level <= this.Level)
{
e.FailReason = GameEvent.EventFailReason.Permission;
return e;
}

sender.CurrentServer.Manager.GetEventHandler().AddEvent(e);
Expand Down Expand Up @@ -367,7 +366,6 @@ public GameEvent Ban(String banReason, Player sender)
if (sender.Level <= this.Level)
{
e.FailReason = GameEvent.EventFailReason.Permission;
return e;
}

sender.CurrentServer.Manager.GetEventHandler().AddEvent(e);
Expand Down
12 changes: 6 additions & 6 deletions SharedLibraryCore/PluginImporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static bool Load(IManager Manager)
if (dllFileNames.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;
}

Expand All @@ -43,7 +43,7 @@ public static bool Load(IManager Manager)
{
var plugin = new ScriptPlugin(fileName);
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);
}

Expand All @@ -66,7 +66,7 @@ public static bool Load(IManager Manager)
Object commandObject = Activator.CreateInstance(assemblyType);
Command newCommand = (Command)commandObject;
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++;
continue;
}
Expand All @@ -82,18 +82,18 @@ public static bool Load(IManager Manager)
{
ActivePlugins.Add(newNotify);
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)
{
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;
}
}
Expand Down
4 changes: 2 additions & 2 deletions SharedLibraryCore/ScriptPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ private async void Watcher_Changed(object sender, FileSystemEventArgs e)
}
catch (Exception ex)
{
Manager.GetLogger().WriteError($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"]} {Name}");
Manager.GetLogger().WriteDebug(ex.Message);
Manager.GetLogger(0).WriteError($"{Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"]} {Name}");
Manager.GetLogger(0).WriteDebug(ex.Message);
}
}

Expand Down
2 changes: 1 addition & 1 deletion SharedLibraryCore/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public Server(IManager mgr, ServerConfiguration config)
IP = config.IPAddress;
Port = config.Port;
Manager = mgr;
Logger = Manager.GetLogger();
Logger = Manager.GetLogger(this.GetHashCode());
ServerConfig = config;
RemoteConnection = new RCon.Connection(IP, Port, Password, Logger);

Expand Down
6 changes: 3 additions & 3 deletions WebfrontCore/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public IActionResult Index()
public IActionResult Error()
{
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
Manager.GetLogger().WriteError($"[Webfront] {exceptionFeature.Error.Message}");
Manager.GetLogger().WriteDebug(exceptionFeature.Path);
Manager.GetLogger().WriteDebug(exceptionFeature.Error.StackTrace);
Manager.GetLogger(0).WriteError($"[Webfront] {exceptionFeature.Error.Message}");
Manager.GetLogger(0).WriteDebug(exceptionFeature.Path);
Manager.GetLogger(0).WriteDebug(exceptionFeature.Error.StackTrace);

ViewBag.Description = Localization["WEBFRONT_ERROR_DESC"];
ViewBag.Title = Localization["WEBFRONT_ERROR_TITLE"];
Expand Down

0 comments on commit b902069

Please sign in to comment.