Files
ArchiSteamFarm/ArchiSteamFarm/NLog/Logging.cs

450 lines
14 KiB
C#
Raw Normal View History

2019-02-16 17:34:17 +01:00
// _ _ _ ____ _ _____
2017-11-18 17:27:06 +01:00
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
2019-01-14 19:11:17 +01:00
// |
2022-01-06 20:22:38 +01:00
// Copyright 2015-2022 Łukasz "JustArchi" Domeradzki
2018-07-27 04:52:14 +02:00
// Contact: JustArchi@JustArchi.net
2019-01-14 19:11:17 +01:00
// |
2018-07-27 04:52:14 +02:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2019-01-14 19:11:17 +01:00
// |
2018-07-27 04:52:14 +02:00
// http://www.apache.org/licenses/LICENSE-2.0
2019-01-14 19:11:17 +01:00
// |
2018-07-27 04:52:14 +02:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2015-10-28 19:21:27 +01:00
2019-02-23 04:31:58 +01:00
using System;
2020-11-11 18:02:17 +01:00
using System.ComponentModel;
using System.Globalization;
2019-05-26 21:17:52 +02:00
using System.IO;
2016-07-04 21:58:50 +02:00
using System.Linq;
2019-02-23 04:31:58 +01:00
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2018-09-08 01:03:55 +02:00
using ArchiSteamFarm.Collections;
using ArchiSteamFarm.Core;
using ArchiSteamFarm.IPC;
2019-02-23 04:31:58 +01:00
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.NLog.Targets;
using ArchiSteamFarm.Steam;
using ArchiSteamFarm.Storage;
using NLog;
using NLog.Config;
using NLog.Targets;
2015-10-25 06:16:50 +01:00
2021-11-10 21:23:24 +01:00
namespace ArchiSteamFarm.NLog;
2021-11-10 21:23:24 +01:00
internal static class Logging {
internal const string NLogConfigurationFile = "NLog.config";
2016-06-10 00:49:44 +02:00
2021-11-10 21:23:24 +01:00
private const byte ConsoleResponsivenessDelay = 250; // In milliseconds
private const string GeneralLayout = $@"${{date:format=yyyy-MM-dd HH\:mm\:ss}}|${{processname}}-${{processid}}|${{level:uppercase=true}}|{LayoutMessage}";
2021-11-10 21:23:24 +01:00
private const string LayoutMessage = @"${logger}|${message}${onexception:inner= ${exception:format=toString,Data}}";
2016-06-10 00:49:44 +02:00
2021-11-10 21:23:24 +01:00
private static readonly ConcurrentHashSet<LoggingRule> ConsoleLoggingRules = new();
private static readonly SemaphoreSlim ConsoleSemaphore = new(1, 1);
2021-05-07 00:06:03 +02:00
2021-11-10 21:23:24 +01:00
private static string Backspace => "\b \b";
2021-11-10 21:23:24 +01:00
private static bool IsUsingCustomConfiguration;
private static bool IsWaitingForUserInput;
2017-06-26 01:37:14 +02:00
2021-11-10 21:23:24 +01:00
internal static void EnableTraceLogging() {
if (IsUsingCustomConfiguration || (LogManager.Configuration == null)) {
return;
}
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
bool reload = false;
2017-06-26 01:37:14 +02:00
2021-11-10 21:23:24 +01:00
foreach (LoggingRule rule in LogManager.Configuration.LoggingRules.Where(static rule => rule.IsLoggingEnabledForLevel(LogLevel.Debug) && !rule.IsLoggingEnabledForLevel(LogLevel.Trace))) {
rule.EnableLoggingForLevel(LogLevel.Trace);
reload = true;
2017-06-26 01:37:14 +02:00
}
2021-11-10 21:23:24 +01:00
if (reload) {
LogManager.ReconfigExistingLoggers();
}
}
2020-11-11 18:02:17 +01:00
2021-11-10 21:23:24 +01:00
internal static async Task<string?> GetUserInput(ASF.EUserInputType userInputType, string botName = SharedInfo.ASF) {
2022-01-23 01:37:43 +01:00
if ((userInputType == ASF.EUserInputType.None) || !Enum.IsDefined(userInputType)) {
2021-11-10 21:23:24 +01:00
throw new InvalidEnumArgumentException(nameof(userInputType), (int) userInputType, typeof(ASF.EUserInputType));
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
if (string.IsNullOrEmpty(botName)) {
throw new ArgumentNullException(nameof(botName));
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
if (Program.Service || (ASF.GlobalConfig?.Headless ?? GlobalConfig.DefaultHeadless)) {
ASF.ArchiLogger.LogGenericWarning(Strings.ErrorUserInputRunningInHeadlessMode);
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
return null;
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
await ConsoleSemaphore.WaitAsync().ConfigureAwait(false);
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
string? result;
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
try {
OnUserInputStart();
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
try {
switch (userInputType) {
case ASF.EUserInputType.Login:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamLogin, botName));
result = ConsoleReadLine();
break;
case ASF.EUserInputType.Password:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamPassword, botName));
result = ConsoleReadLineMasked();
break;
case ASF.EUserInputType.SteamGuard:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamGuard, botName));
result = ConsoleReadLine();
break;
case ASF.EUserInputType.SteamParentalCode:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamParentalCode, botName));
result = ConsoleReadLineMasked();
break;
case ASF.EUserInputType.TwoFactorAuthentication:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteam2FA, botName));
result = ConsoleReadLine();
break;
default:
ASF.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.WarningUnknownValuePleaseReport, nameof(userInputType), userInputType));
return null;
2019-02-23 04:31:58 +01:00
}
2021-11-10 21:23:24 +01:00
if (!Console.IsOutputRedirected) {
Console.Clear(); // For security purposes
2019-05-26 21:17:52 +02:00
}
} catch (Exception e) {
2021-11-10 21:23:24 +01:00
OnUserInputEnd();
2019-05-26 21:17:52 +02:00
ASF.ArchiLogger.LogGenericException(e);
2021-11-10 21:23:24 +01:00
return null;
} finally {
OnUserInputEnd();
2019-05-26 21:17:52 +02:00
}
2021-11-10 21:23:24 +01:00
} finally {
ConsoleSemaphore.Release();
}
2019-05-26 21:17:52 +02:00
2021-11-10 21:23:24 +01:00
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
return !string.IsNullOrEmpty(result) ? result!.Trim() : null;
}
2018-12-15 00:27:15 +01:00
2021-11-10 21:23:24 +01:00
internal static void InitCoreLoggers(bool uniqueInstance) {
try {
if ((Directory.GetCurrentDirectory() != AppContext.BaseDirectory) && File.Exists(NLogConfigurationFile)) {
IsUsingCustomConfiguration = true;
2021-11-10 21:23:24 +01:00
LogManager.Configuration = new XmlLoggingConfiguration(NLogConfigurationFile);
}
2021-11-10 21:23:24 +01:00
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
if (IsUsingCustomConfiguration) {
2021-11-10 21:23:24 +01:00
InitConsoleLoggers();
LogManager.ConfigurationChanged += OnConfigurationChanged;
2021-11-10 21:23:24 +01:00
return;
}
if (uniqueInstance) {
try {
if (!Directory.Exists(SharedInfo.ArchivalLogsDirectory)) {
Directory.CreateDirectory(SharedInfo.ArchivalLogsDirectory);
2019-07-27 19:22:22 +02:00
}
2021-11-10 21:23:24 +01:00
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
2019-07-27 19:22:22 +02:00
#pragma warning disable CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
2021-11-10 21:23:24 +01:00
FileTarget fileTarget = new("File") {
ArchiveFileName = Path.Combine("${currentdir}", SharedInfo.ArchivalLogsDirectory, SharedInfo.ArchivalLogFile),
ArchiveNumbering = ArchiveNumberingMode.Rolling,
ArchiveOldFileOnStartup = true,
CleanupFileName = false,
ConcurrentWrites = false,
DeleteOldFileOnStartup = true,
FileName = Path.Combine("${currentdir}", SharedInfo.LogFile),
Layout = GeneralLayout,
MaxArchiveFiles = 10
};
#pragma warning restore CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
LogManager.Configuration.AddTarget(fileTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));
LogManager.ReconfigExistingLoggers();
2016-06-10 00:49:44 +02:00
}
2021-11-10 21:23:24 +01:00
InitConsoleLoggers();
}
2018-01-31 02:42:23 +01:00
internal static void InitEmergencyLoggers() {
if (LogManager.Configuration != null) {
IsUsingCustomConfiguration = true;
return;
}
// This is a temporary, bare, file-less configuration that must work until we're able to initialize it properly
ConfigurationItemFactory.Default.ParseMessageTemplates = false;
LoggingConfiguration config = new();
#pragma warning disable CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
ColoredConsoleTarget coloredConsoleTarget = new("ColoredConsole") { Layout = GeneralLayout };
#pragma warning restore CA2000 // False positive, we're adding this disposable object to the global scope, so we can't dispose it
config.AddTarget(coloredConsoleTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, coloredConsoleTarget));
LogManager.Configuration = config;
}
2021-11-10 21:23:24 +01:00
internal static void InitHistoryLogger() {
if (LogManager.Configuration == null) {
return;
}
2021-11-10 21:23:24 +01:00
HistoryTarget? historyTarget = LogManager.Configuration.AllTargets.OfType<HistoryTarget>().FirstOrDefault();
2021-11-10 21:23:24 +01:00
if ((historyTarget == null) && !IsUsingCustomConfiguration) {
historyTarget = new HistoryTarget("History") {
Layout = GeneralLayout,
MaxCount = 20
};
2018-01-31 02:42:23 +01:00
2021-11-10 21:23:24 +01:00
LogManager.Configuration.AddTarget(historyTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, historyTarget));
2018-01-31 02:42:23 +01:00
2021-11-10 21:23:24 +01:00
LogManager.ReconfigExistingLoggers();
2018-01-31 02:42:23 +01:00
}
2021-11-10 21:23:24 +01:00
ArchiKestrel.OnNewHistoryTarget(historyTarget);
}
2021-11-10 21:23:24 +01:00
internal static void StartInteractiveConsole() {
Utilities.InBackground(HandleConsoleInteractively, true);
ASF.ArchiLogger.LogGenericInfo(Strings.InteractiveConsoleEnabled);
}
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
private static async Task BeepUntilCanceled(CancellationToken cancellationToken, byte secondsDelay = 30) {
if (secondsDelay == 0) {
throw new ArgumentOutOfRangeException(nameof(secondsDelay));
}
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
while (!cancellationToken.IsCancellationRequested) {
try {
await Task.Delay(secondsDelay * 1000, cancellationToken).ConfigureAwait(false);
} catch (TaskCanceledException) {
return;
2020-11-11 21:06:17 +01:00
}
2021-11-10 21:23:24 +01:00
Console.Beep();
2020-11-11 21:06:17 +01:00
}
2021-11-10 21:23:24 +01:00
}
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
private static string? ConsoleReadLine() {
using CancellationTokenSource cts = new();
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
try {
CancellationToken token = cts.Token;
2016-07-04 21:58:50 +02:00
2021-11-10 21:23:24 +01:00
Utilities.InBackground(() => BeepUntilCanceled(token));
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
return Console.ReadLine();
} finally {
cts.Cancel();
2019-02-23 04:31:58 +01:00
}
2021-11-10 21:23:24 +01:00
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
private static string ConsoleReadLineMasked(char mask = '*') {
using CancellationTokenSource cts = new();
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
try {
CancellationToken token = cts.Token;
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
Utilities.InBackground(() => BeepUntilCanceled(token));
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
StringBuilder result = new();
2020-11-11 21:19:29 +01:00
2021-11-10 21:23:24 +01:00
ConsoleKeyInfo keyInfo;
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter) {
if (!char.IsControl(keyInfo.KeyChar)) {
result.Append(keyInfo.KeyChar);
Console.Write(mask);
} else if ((keyInfo.Key == ConsoleKey.Backspace) && (result.Length > 0)) {
result.Length--;
2020-11-11 21:06:17 +01:00
2021-11-10 21:23:24 +01:00
if (Console.CursorLeft == 0) {
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
} else {
Console.Write(Backspace);
2019-02-23 04:31:58 +01:00
}
}
2021-11-10 21:23:24 +01:00
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
Console.WriteLine();
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
return result.ToString();
} finally {
cts.Cancel();
2016-07-04 21:58:50 +02:00
}
2021-11-10 21:23:24 +01:00
}
private static async Task HandleConsoleInteractively() {
while (!Program.ShutdownSequenceInitialized) {
try {
if (IsWaitingForUserInput || !Console.KeyAvailable) {
continue;
}
await ConsoleSemaphore.WaitAsync().ConfigureAwait(false);
2016-07-04 21:58:50 +02:00
2019-02-23 04:31:58 +01:00
try {
2021-11-10 21:23:24 +01:00
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key != ConsoleKey.C) {
2019-02-23 04:31:58 +01:00
continue;
}
2021-11-10 21:23:24 +01:00
OnUserInputStart();
2016-07-04 21:58:50 +02:00
2019-02-23 04:31:58 +01:00
try {
2021-11-10 21:23:24 +01:00
Console.Write($@">> {Strings.EnterCommand}");
string? command = ConsoleReadLine();
2018-05-17 09:54:22 +02:00
2021-11-10 21:23:24 +01:00
if (string.IsNullOrEmpty(command)) {
2019-02-23 04:31:58 +01:00
continue;
}
2016-07-04 21:58:50 +02:00
2021-11-10 21:23:24 +01:00
string? commandPrefix = ASF.GlobalConfig != null ? ASF.GlobalConfig.CommandPrefix : GlobalConfig.DefaultCommandPrefix;
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
// ReSharper disable RedundantSuppressNullableWarningExpression - required for .NET Framework
if (!string.IsNullOrEmpty(commandPrefix) && command!.StartsWith(commandPrefix!, StringComparison.Ordinal)) {
// ReSharper restore RedundantSuppressNullableWarningExpression - required for .NET Framework
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
if (command.Length == commandPrefix!.Length) {
// If the message starts with command prefix and is of the same length as command prefix, then it's just empty command trigger, useless
2019-02-23 04:31:58 +01:00
continue;
}
2021-11-10 21:23:24 +01:00
command = command[commandPrefix.Length..];
}
2019-02-23 05:02:22 +01:00
2021-11-10 21:23:24 +01:00
Bot? targetBot = Bot.Bots?.OrderBy(static bot => bot.Key, Bot.BotsComparer).Select(static bot => bot.Value).FirstOrDefault();
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
if (targetBot == null) {
Console.WriteLine($@"<< {Strings.ErrorNoBotsDefined}");
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
continue;
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
Console.WriteLine($@"<> {Strings.Executing}");
2019-02-23 04:31:58 +01:00
2021-11-10 22:05:08 +01:00
// ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework
string? response = await targetBot.Commands.Response(EAccess.Owner, command!).ConfigureAwait(false);
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
if (string.IsNullOrEmpty(response)) {
ASF.ArchiLogger.LogNullError(nameof(response));
Console.WriteLine(Strings.ErrorIsEmpty, nameof(response));
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
continue;
2019-02-23 04:31:58 +01:00
}
2021-11-10 21:23:24 +01:00
Console.WriteLine($@"<< {response}");
2019-02-23 04:31:58 +01:00
} finally {
2021-11-10 21:23:24 +01:00
OnUserInputEnd();
2019-02-23 04:31:58 +01:00
}
} finally {
2021-11-10 21:23:24 +01:00
ConsoleSemaphore.Release();
2019-02-23 04:31:58 +01:00
}
2021-11-10 21:23:24 +01:00
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
return;
} finally {
await Task.Delay(ConsoleResponsivenessDelay).ConfigureAwait(false);
2018-05-17 09:54:22 +02:00
}
2016-07-04 21:58:50 +02:00
}
2021-11-10 21:23:24 +01:00
}
2021-11-10 21:23:24 +01:00
private static void InitConsoleLoggers() {
ConsoleLoggingRules.Clear();
2018-05-17 09:54:22 +02:00
2021-11-10 21:23:24 +01:00
foreach (LoggingRule loggingRule in LogManager.Configuration.LoggingRules.Where(static loggingRule => loggingRule.Targets.Any(static target => target is ColoredConsoleTarget or ConsoleTarget))) {
ConsoleLoggingRules.Add(loggingRule);
2016-07-04 22:03:12 +02:00
}
2021-11-10 21:23:24 +01:00
}
2021-11-10 21:23:24 +01:00
private static void OnConfigurationChanged(object? sender, LoggingConfigurationChangedEventArgs e) {
2021-12-12 01:12:54 +01:00
ArgumentNullException.ThrowIfNull(e);
2021-11-10 21:23:24 +01:00
InitConsoleLoggers();
2018-01-31 02:42:23 +01:00
2021-11-10 21:23:24 +01:00
if (IsWaitingForUserInput) {
OnUserInputStart();
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
HistoryTarget? historyTarget = LogManager.Configuration.AllTargets.OfType<HistoryTarget>().FirstOrDefault();
ArchiKestrel.OnNewHistoryTarget(historyTarget);
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
private static void OnUserInputEnd() {
IsWaitingForUserInput = false;
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
if (ConsoleLoggingRules.Count == 0) {
return;
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
bool reconfigure = false;
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
foreach (LoggingRule consoleLoggingRule in ConsoleLoggingRules.Where(static consoleLoggingRule => !LogManager.Configuration.LoggingRules.Contains(consoleLoggingRule))) {
LogManager.Configuration.LoggingRules.Add(consoleLoggingRule);
reconfigure = true;
2019-02-23 04:31:58 +01:00
}
2021-11-10 21:23:24 +01:00
if (reconfigure) {
LogManager.ReconfigExistingLoggers();
}
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
private static void OnUserInputStart() {
IsWaitingForUserInput = true;
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
if (ConsoleLoggingRules.Count == 0) {
return;
}
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
bool reconfigure = false;
2019-02-23 04:31:58 +01:00
2021-11-10 21:23:24 +01:00
foreach (LoggingRule _ in ConsoleLoggingRules.Where(static consoleLoggingRule => LogManager.Configuration.LoggingRules.Remove(consoleLoggingRule))) {
reconfigure = true;
}
if (reconfigure) {
LogManager.ReconfigExistingLoggers();
2019-02-23 04:31:58 +01:00
}
2016-06-10 00:49:44 +02:00
}
}