Логирование.

This commit is contained in:
ksenianeva 2022-12-02 00:04:23 +04:00
parent a8456abc36
commit 4ab74bde46
9 changed files with 131 additions and 26 deletions

View File

@ -8,6 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<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>

View File

@ -8,6 +8,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using static System.Windows.Forms.DataFormats; using static System.Windows.Forms.DataFormats;
using Microsoft.Extensions.Logging;
namespace ContainerShip namespace ContainerShip
{ {
@ -28,9 +29,14 @@ namespace ContainerShip
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormMapWithSetShips() /// /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormMapWithSetShips(ILogger<FormMapWithSetShips> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
ComboBoxSelectorMap.Items.Clear(); ComboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
@ -97,14 +103,21 @@ namespace ContainerShip
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); {
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
} }
else catch (ShipNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}") ;
} }
} }
/// <summary> /// <summary>
@ -179,6 +192,7 @@ namespace ContainerShip
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
} }
/// <summary> /// <summary>
/// Выбор карты /// Выбор карты
@ -212,13 +226,14 @@ namespace ContainerShip
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -227,14 +242,15 @@ namespace ContainerShip
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps(); ReloadMaps();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -71,7 +71,7 @@ namespace ContainerShip
foreach (var ship in _setShips.GetShips()) foreach (var ship in _setShips.GetShips())
{ {
return _map.CreateMap(_pictureWidth, _pictureHeight, ship); return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
} }
return new(_pictureWidth, _pictureHeight); return new(_pictureWidth, _pictureHeight);
} }
public string GetData(char separatorType, char separatorData) public string GetData(char separatorType, char separatorData)

View File

@ -104,7 +104,7 @@ namespace ContainerShip
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns></returns> /// <returns></returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -119,19 +119,17 @@ namespace ContainerShip
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw); sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка нформации по автомобилям на парковках из файла /// Загрузка нформации по автомобилям на парковках из файла
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
using (FileStream fs = new(filename, FileMode.Open)) using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs)) using (StreamReader sr = new StreamReader(fs))
@ -139,7 +137,10 @@ namespace ContainerShip
string line; string line;
line = sr.ReadLine(); line = sr.ReadLine();
line.Trim(); line.Trim();
if (line != "MapsCollection") return false; if (line != "MapsCollection")
{
throw new Exception("Неправильный формат данных в файле");
}
_mapStorages.Clear(); _mapStorages.Clear();
while ((line = sr.ReadLine()) != null) while ((line = sr.ReadLine()) != null)
{ {
@ -158,7 +159,6 @@ namespace ContainerShip
_mapStorages.Add(elem[0], new MapWithSetShipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map)); _mapStorages.Add(elem[0], new MapWithSetShipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
return true;
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
namespace ContainerShip namespace ContainerShip
{ {
internal static class Program internal static class Program
@ -11,7 +16,27 @@ namespace ContainerShip
// 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 FormMapWithSetShips()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetShips>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetShips>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.AddSerilog();
});
} }
} }
} }

View File

@ -44,8 +44,10 @@ namespace ContainerShip
/// <returns></returns> /// <returns></returns>
public int Insert(T ship, int position) public int Insert(T ship, int position)
{ {
if (position < 0 || position >= _maxCount) return -1; if (position < 0 || position >= _maxCount || _places.Count + 1 >= _maxCount)
if (_places.Count + 1 >= _maxCount) return -1; {
throw new StorageOverflowException(_maxCount);
}
_places.Add(ship); _places.Add(ship);
return position; return position;
} }
@ -58,7 +60,7 @@ namespace ContainerShip
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
{ {
return null; throw new ShipNotFoundException(position);
} }
T ship = _places[position]; T ship = _places[position];
_places.RemoveAt(position); _places.RemoveAt(position);

View File

@ -1,12 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ContainerShip namespace ContainerShip
{ {
internal class ShipNotFoundException [Serializable]
internal class ShipNotFoundException : ApplicationException
{ {
public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public ShipNotFoundException() : base() { }
public ShipNotFoundException(string message) : base(message) { }
public ShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
} }
} }

View File

@ -1,12 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ContainerShip namespace ContainerShip
{ {
internal class StorageOverflowException [Serializable]
internal class StorageOverflowException : ApplicationException
{ {
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
} }
} }

View File

@ -0,0 +1,24 @@
{
"exclude": [
"/bin",
"/bower_components",
"/jspm_packages",
"/node_modules",
"/obj",
"/platforms"
],
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "Logs/log.txt" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Sample"
}
}
}