Вроде работающий логгер

This commit is contained in:
Павел Ладягин 2024-05-05 13:56:19 +04:00
parent 923aafca36
commit 31570fb993
4 changed files with 135 additions and 16 deletions

View File

@ -1,4 +1,6 @@
using ProjectAirplaneWithRadar.CollectionGenericObjects; using System.Numerics;
using Microsoft.Extensions.Logging;
using ProjectAirplaneWithRadar.CollectionGenericObjects;
using ProjectAirplaneWithRadar.Drawnings; using ProjectAirplaneWithRadar.Drawnings;
using ProjectAirplaneWithRadar.Exceptions; using ProjectAirplaneWithRadar.Exceptions;
@ -19,13 +21,20 @@ namespace ProjectAirplaneWithRadar
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormAirplaneCollection() public FormAirplaneCollection(ILogger<FormAirplaneCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -65,15 +74,18 @@ namespace ProjectAirplaneWithRadar
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
} }
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
catch (ObjectNotFoundException ex) catch (ObjectNotFoundException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -102,13 +114,16 @@ namespace ProjectAirplaneWithRadar
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
} }
} catch (PositionOutOfCollectionException ex) } catch (PositionOutOfCollectionException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} catch (ObjectNotFoundException ex) } catch (ObjectNotFoundException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -187,14 +202,34 @@ namespace ProjectAirplaneWithRadar
return; return;
} }
//CollectionType collectionType = CollectionType.None;
//if (radioButtonMassive.Checked)
// collectionType = CollectionType.Massive;
//else if (radioButtonList.Checked)
// collectionType = CollectionType.List;
//_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
//RefreshListBoxItems();
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive; collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked) else if (radioButtonList.Checked)
{
collectionType = CollectionType.List; collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -209,13 +244,28 @@ namespace ProjectAirplaneWithRadar
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
//if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
//{
// return;
//}
//_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
//RefreshListBoxItems();
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@ -276,10 +326,12 @@ namespace ProjectAirplaneWithRadar
{ {
_storageCollection.SaveData(saveFileDialog.FileName); _storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
catch(Exception ex) catch(Exception ex)
{ {
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -298,10 +350,12 @@ namespace ProjectAirplaneWithRadar
_storageCollection.LoadData(openFileDialog.FileName); _storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
catch(Exception ex) catch(Exception ex)
{ {
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirplaneWithRadar namespace ProjectAirplaneWithRadar
{ {
internal static class Program internal static class Program
@ -11,7 +16,33 @@ namespace ProjectAirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormAirplaneCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormAirplaneCollection>());
} }
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormAirplaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder().AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
}
} }
} }

View File

@ -8,6 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +36,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}