Skip to content

Commit

Permalink
Добавлено переключение уровней логирования в NLog.config разных проду…
Browse files Browse the repository at this point in the history
…ктов.
  • Loading branch information
Zymlex committed May 10, 2020
1 parent cd9b62d commit e0bebd3
Show file tree
Hide file tree
Showing 8 changed files with 360 additions and 115 deletions.
4 changes: 2 additions & 2 deletions DetailedLogSwitcher/DetailedLogSwitcher.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

<ItemGroup>
Expand Down
15 changes: 15 additions & 0 deletions DetailedLogSwitcher/Helper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using static System.Console;

namespace DetailedLogSwitcher
{
public class Helper
{
internal static void Pause() => ReadKey(true);

internal static void ShowError(string message)
{
WriteLine(message);
Pause();
}
}
}
2 changes: 1 addition & 1 deletion DetailedLogSwitcher/Json.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace DetailedLogSwitcher
{
public class Config
public class GlobalSettings
{

[JsonProperty("clnMainGroup")]
Expand Down
124 changes: 124 additions & 0 deletions DetailedLogSwitcher/Logic/Search.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Microsoft.Win32;
using Newtonsoft.Json;
using static System.Console;
using static DetailedLogSwitcher.Result;

namespace DetailedLogSwitcher
{
public static class SearchConfigs
{
internal static Result SearchNLogs(out List<string> nLogPaths)
{
WriteLine("Получение установленных программ...\n");

nLogPaths = new List<string>();

using RegistryKey zlKey = Registry.CurrentUser.OpenSubKey(@"Software\ZennoLab");
if (zlKey != null)
{
string[] langs = {"RU", "EN", "CN"};
foreach (string lang in langs)
{
using RegistryKey langKey = zlKey.OpenSubKey(lang);
if(langKey == null) continue;

string[] products = langKey.GetSubKeyNames();
foreach (string product in products)
{
using RegistryKey productKey = langKey.OpenSubKey(product);
if(productKey == null) continue;

string[] versions = productKey.GetSubKeyNames();
foreach (string ver in versions)
{
using RegistryKey verKey = productKey.OpenSubKey(ver);

if(verKey == null || (string)verKey.GetValue("SuccessInstall") != "True") continue;

string productPath = (string)verKey.GetValue("InstallDir");
if (!string.IsNullOrEmpty(productPath))
{
string nLogPath = productPath + @"\Progs\NLog.config";
if (File.Exists(nLogPath))
{
nLogPaths.Add(nLogPath);
WriteLine(@"Найден NLog.config версии " + ver);
}
else
{
WriteLine($"Продукт {product} найден в реестре, но NLog.config не найден по пути: " + nLogPath);
continue;
}
}
else
{
WriteLine("Продукт найден в реестре, но InstallDir не установлен.");
continue;
}
}
}
}
}
else
{
return Error(@"Ни одна программа не установлена. Не найден: HKCU\Software\ZennoLab");
}

if (nLogPaths.Count == 0)
return Error("Ни один NLog.config не найден.");

return Ok(nLogPaths);
}

internal static Result SearchGlobalSettings(out List<string> globalSettingsPaths)
{
WriteLine("\nПроверка наличия глобальных настроек...\n");

globalSettingsPaths = new List<string>();

string appDataPath = Environment.GetEnvironmentVariable("APPDATA");

string[] versions = {"5", "7"};

foreach (string ver in versions)
{
string path = $@"{appDataPath}\ZennoLab\ZennoPoster\{ver}\Settings\globalsettings.settings.json";

if (File.Exists(path))
{
globalSettingsPaths.Add(path);
WriteLine($@"Глобальный конфиг {ver} версии найден.");
}
}

if (globalSettingsPaths.Count == 0)
return Error("Ни один из глобальных конфигов не найден!");

return Ok(globalSettingsPaths);

#region

// string zennoposterPath = Environment.GetEnvironmentVariable("ZennoPosterCurrentPath");
//
// if(string.IsNullOrEmpty(zennoposterPath))
// WriteLine("Переменная окружения ZennoPosterCurrentPath не установлена. Поиск путей по умолчанию...");
//
// string[] zennolabPaths = {@"C:\Program Files\ZennoLab", @"C:\Program Files (x86)\ZennoLab"};
// string[] langs = {"EN", "RU", /*"CN"*/};
//
// foreach (string zlPath in zennolabPaths)
// {
// foreach (string lang in langs)
// {
// string path = $@"{zlPath}\{lang}";
// }
// }

#endregion
}
}
}
114 changes: 114 additions & 0 deletions DetailedLogSwitcher/Logic/Setup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Newtonsoft.Json;
using static System.Console;
using static DetailedLogSwitcher.NlogState;
using Formatting = Newtonsoft.Json.Formatting;

namespace DetailedLogSwitcher
{
public static class NlogState
{
public const string Trace = "Trace";
public const string Debug = "Debug";
}

public static class Setup
{
public static void ConfigureGlobalSettings(List<string> paths, bool newState)
{
foreach (string path in paths)
{
string json = File.ReadAllText(path);
GlobalSettings[] cfg = JsonConvert.DeserializeObject<GlobalSettings[]>(json);

foreach (GlobalSettings c in cfg)
{
if (c.ClnName == "DetailedLogEnabled" && c.ClnSubGroup == "Log")
{
string newStateStr = newState.ToString();

if (c.ClnValue == newStateStr)
{
WriteLine($"Подробный лог в глобальной настройке уже {(newState ? "включён" : "выключен")} по пути: " + path);
continue;
}
else
{
c.ClnValue = newStateStr;
WriteLine("Включён подробный лог в глобальных настройках по пути: " + path);

string output = JsonConvert.SerializeObject(cfg, Formatting.Indented);
File.WriteAllText(path, output);
break;
}
}
}
}
}

public static void ConfigureNLogs(List<string> paths, string newState)
{
foreach (string path in paths)
{
XmlDocument doc = new XmlDocument {PreserveWhitespace = true};
doc.Load(path);
XPathNavigator navigator = doc.CreateNavigator();

const string xPath = "a:nlog/a:rules/a:logger/@minlevel";

XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("a", "http://www.nlog-project.org/schemas/NLog.xsd");
XPathExpression query = navigator.Compile(xPath);
query.SetContext(manager);
XPathNodeIterator nodes = navigator.Select(query);

bool isEdited = false;

if (nodes.Count != 0)
{
while (nodes.MoveNext())
{
XPathNavigator nav = nodes.Current;
string val = nav.Value;
if(val == "Fatal") continue;
if (val != newState)
{
nav.SetValue(newState);
isEdited = true;
}
}

if (isEdited)
{
var writer = XmlWriter.Create(path, new XmlWriterSettings()
{
Indent = false,
Encoding = Encoding.Default,
//NewLineOnAttributes = false,
CloseOutput = true,
CheckCharacters = true,
//NewLineHandling = NewLineHandling.None,
});
using (writer) doc.Save(writer);

WriteLine("Настроен NLog.config по пути: " + path);
}
else
{
WriteLine("NLog.config уже настроен по пути: " + path);
}
}
else
{
WriteLine($"Не были получены элементы NLog.config по пути: " + path);
continue;
}
}
}
}
}
75 changes: 75 additions & 0 deletions DetailedLogSwitcher/Main.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Newtonsoft.Json;
using static System.Console;
using static DetailedLogSwitcher.Helper;
using static DetailedLogSwitcher.SearchConfigs;

namespace DetailedLogSwitcher
{
internal static class Program
{
private static void Main(string[] args)
{
try
{
Result gsResult = SearchGlobalSettings(out List<string> globalSettingsPaths);
switch(gsResult)
{
case Error result:
ShowError(result.Message);
return;
}

Result nLogsResult = SearchNLogs(out List<string> existNLogs);
switch(nLogsResult)
{
case Error result:
ShowError(result.Message);
return;
}

for (int i = 1;; i++)
{
WriteLine("\nУправление:\n1 - включить\n2 - выключить\nq - выйти");
Write("\nВвод: ");
ConsoleKeyInfo keyInfo = ReadKey();
WriteLine();

switch (keyInfo.Key)
{
case ConsoleKey.Q:
return;
case ConsoleKey.D1: // Включение
Setup.ConfigureGlobalSettings(globalSettingsPaths, true);
Setup.ConfigureNLogs(existNLogs, NlogState.Trace);
return;
case ConsoleKey.D2: // Выключение
Setup.ConfigureGlobalSettings(globalSettingsPaths, false);
Setup.ConfigureNLogs(existNLogs, NlogState.Debug);
return;
}

if (i == 5)
{
WriteLine("\nМножественный неверный ввод. Завершение работы...");
Thread.Sleep(2000);
return;
}

Thread.Sleep(250);
}
}
catch (Exception e)
{
WriteLine(e);
}
finally
{
Pause();
}
}
}
}
Loading

0 comments on commit e0bebd3

Please sign in to comment.