Fixed the cleanup of the log files generated by the auto processes (Backup, Update and Shutdown/Restart)

Added new Log settings which allow you to turn if on/off and set the number of days/files to retain
Language file updates
This commit is contained in:
Brett Hewitson 2021-12-18 21:31:36 +10:00
parent f582e1e72a
commit dace70a37c
29 changed files with 821 additions and 431 deletions

View file

@ -7,6 +7,10 @@ namespace ServerManagerTool.DiscordBot.Models
{
public LogLevel LogLevel { get; set; } = LogLevel.Info;
public int MaxArchiveDays { get; set; } = 30;
public int MaxArchiveFiles { get; set; } = 30;
public string DiscordToken { get; set; } = string.Empty;
public string CommandPrefix { get; set; } = string.Empty;

View file

@ -21,6 +21,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
<PackageReference Include="NLog" Version="4.7.2" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />

View file

@ -1,6 +1,9 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using NLog;
using NLog.Config;
using NLog.Targets;
using ServerManagerTool.DiscordBot.Models;
using System;
using System.IO;
@ -10,22 +13,21 @@ namespace ServerManagerTool.DiscordBot.Services
{
public class LoggingService
{
private readonly Logger _logger;
private readonly DiscordSocketClient _client;
private readonly CommandService _commands;
private readonly DiscordBotConfig _botConfig;
private string LogDirectory { get; }
private string LogFile => Path.Combine(LogDirectory, $"ServerManager_DiscordBot.{DateTime.Now:yyyyMMdd}.log");
public LoggingService(DiscordSocketClient client, CommandService commands, DiscordBotConfig botConfig)
{
_client = client;
_commands = commands;
_botConfig = botConfig;
// Get the data directory from the config file
var rootDirectory = _botConfig.DataDirectory ?? AppContext.BaseDirectory;
LogDirectory = Path.Combine(rootDirectory, "logs");
var logFilePath = Path.Combine(_botConfig.DataDirectory ?? AppContext.BaseDirectory, "logs");
_logger = GetLogger(logFilePath, "", "ServerManager_DiscordBot", LogLevel.Debug, LogLevel.Fatal, _botConfig.MaxArchiveFiles, _botConfig.MaxArchiveDays);
Console.WriteLine($"{DateTime.Now:HH:mm:ss.ffff} [INFO] Logging Enabled: {LogManager.IsLoggingEnabled()}");
_client.Log += OnLogAsync;
_commands.Log += OnLogAsync;
@ -33,25 +35,62 @@ namespace ServerManagerTool.DiscordBot.Services
internal async Task OnLogAsync(LogMessage message)
{
// Create the log directory if it doesn't exist
if (!Directory.Exists(LogDirectory))
switch (message.Severity)
{
Directory.CreateDirectory(LogDirectory);
case LogSeverity.Critical:
_logger?.Fatal($"{message.Source}: {message.Exception?.ToString() ?? message.Message}");
break;
case LogSeverity.Error:
_logger?.Error($"{message.Source}: {message.Exception?.ToString() ?? message.Message}");
break;
case LogSeverity.Warning:
_logger?.Warn($"{message.Source}: {message.Exception?.ToString() ?? message.Message}");
break;
case LogSeverity.Info:
_logger?.Info($"{message.Source}: {message.Exception?.ToString() ?? message.Message}");
break;
case LogSeverity.Verbose:
case LogSeverity.Debug:
_logger?.Debug($"{message.Source}: {message.Exception?.ToString() ?? message.Message}");
break;
}
// Create today's log file if it doesn't exist
if (!File.Exists(LogFile))
{
File.Create(LogFile).Dispose();
}
var logText = $"{DateTime.Now:HH:mm:ss:ffff} [{message.Severity}] {message.Source}: {message.Exception?.ToString() ?? message.Message}";
// Write the log text to a file
File.AppendAllText(LogFile, logText + "\n");
// Write the log text to the console
await Console.Out.WriteLineAsync(logText);
await Console.Out.WriteLineAsync($"{DateTime.Now:HH:mm:ss.ffff} [{message.Severity}] {message.Source}: {message.Exception?.ToString() ?? message.Message}");
}
private static Logger GetLogger(string logFilePath, string logType, string logName, LogLevel minLevel, LogLevel maxLevel, int maxArchiveFiles, int maxArchiveDays)
{
if (string.IsNullOrWhiteSpace(logFilePath) || string.IsNullOrWhiteSpace(logName))
return null;
var loggerName = $"{logType ?? string.Empty}_{logName}".Replace(" ", "_");
if (LogManager.Configuration.FindTargetByName(loggerName) is null)
{
if (!Directory.Exists(logFilePath))
Directory.CreateDirectory(logFilePath);
var logFile = new FileTarget(loggerName)
{
FileName = Path.Combine(logFilePath, $"{logName}.log"),
Layout = "${time} [${level:uppercase=true}] ${message}",
ArchiveFileName = Path.Combine(logFilePath, $"{logName}.{{#}}.log"),
ArchiveNumbering = ArchiveNumberingMode.Date,
ArchiveEvery = FileArchivePeriod.Day,
ArchiveDateFormat = "yyyyMMdd",
ArchiveOldFileOnStartup = true,
MaxArchiveFiles = maxArchiveFiles,
MaxArchiveDays = maxArchiveDays,
};
LogManager.Configuration.AddTarget(loggerName, logFile);
var rule = new LoggingRule(loggerName, minLevel, maxLevel, logFile);
LogManager.Configuration.LoggingRules.Add(rule);
LogManager.ReconfigExistingLoggers();
}
return LogManager.GetLogger(loggerName);
}
}
}