Сделал с nlog

This commit is contained in:
gg12 darfren 2023-11-27 20:02:51 +04:00
parent cb5c91f884
commit 157ab08659
5 changed files with 78 additions and 17 deletions

View File

@ -1,4 +1,5 @@
using Monorail.DrawningObjects;
using Microsoft.Extensions.Logging;
using Monorail.DrawningObjects;
using Monorail.Exceptions;
using Monorail.Generics;
using Monorail.MovementStrategy;
@ -12,18 +13,21 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Monorail
{
public partial class FormMonorailCollection : Form
{
private readonly MonorailGenericStorage _storage;
private readonly ILogger _logger;
public FormMonorailCollection()
public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
{
InitializeComponent();
_storage = new MonorailGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
@ -68,6 +72,7 @@ namespace Monorail
{
bool q = obj + m;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowMonorails();
}
@ -96,17 +101,23 @@ namespace Monorail
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
int pos = Convert.ToInt32(maskedTextBox.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowMonorails();
}
catch (MonorailNotFoundException ex)
{
MessageBox.Show(ex.Message);
}
catch(FormatException ex)
{
MessageBox.Show("Введите число");
}
}
private void updateCollectionButton_Click(object sender, EventArgs e)
@ -137,12 +148,14 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowMonorail
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
string name = listBoxStorages.SelectedItem.ToString()
?? string.Empty;
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
@ -157,6 +170,7 @@ MessageBoxIcon.Question) == DialogResult.Yes)
}
_storage.AddSet(storageAddNameBox.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {storageAddNameBox.Text}");
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
@ -168,6 +182,7 @@ MessageBoxIcon.Question) == DialogResult.Yes)
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
@ -187,7 +202,8 @@ MessageBoxIcon.Question) == DialogResult.Yes)
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach(var collection in _storage.Keys)
_logger.LogInformation($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}

View File

@ -6,6 +6,11 @@
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -21,4 +26,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -70,7 +70,7 @@ StringSplitOptions.RemoveEmptyEntries);
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@ -79,11 +79,11 @@ StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("MonorailStorage"))
{
throw new Exception("Неверный формат данных");
throw new IOException("Неверный формат данных");
}
_monorailStorages.Clear();
do
@ -107,7 +107,7 @@ StringSplitOptions.RemoveEmptyEntries);
{
if (!(collection + monorail))
{
throw new Exception("Ошибка добавления в коллекцию");
return false;
}
}
}

View File

@ -1,23 +1,43 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Monorail
{
static class Program
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMonorailCollection());
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider =
services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMonorailCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMonorailCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="toFile" fileName="${basedir}/monoraillog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
<logger name="*" minlevel="Warning" maxlevel ="Warning" writeTo="tofile" />
</rules>
</nlog>
</configuration>