Логирование
This commit is contained in:
parent
8b9af3a55b
commit
75c271070a
@ -9,6 +9,7 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using static System.Windows.Forms.DataFormats;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace WarmlyShip
|
||||
{
|
||||
@ -25,9 +26,11 @@ namespace WarmlyShip
|
||||
{"Карта речки c камнями",new RiverMap() }
|
||||
};
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
public FormMapWithSetShip()
|
||||
private ILogger _logger;
|
||||
public FormMapWithSetShip(ILogger<FormMapWithSetShip> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logger = logger;
|
||||
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
|
||||
comboBoxSelectorMap.Items.Clear();
|
||||
foreach (var elem in _mapDict)
|
||||
@ -95,19 +98,23 @@ namespace WarmlyShip
|
||||
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(drawningShip) != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation("Добавлен объект {@Ship}", drawningShip);
|
||||
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, drawningShip);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
@ -145,22 +152,27 @@ namespace WarmlyShip
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
try
|
||||
{
|
||||
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
|
||||
var deletedShip = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||
if (deletedShip != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation("Из текущей карты удалён объект {@Ship}", deletedShip);
|
||||
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (ShipNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
|
||||
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
||||
}
|
||||
}
|
||||
@ -226,11 +238,13 @@ namespace WarmlyShip
|
||||
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
|
||||
return;
|
||||
}
|
||||
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
|
||||
{
|
||||
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
|
||||
return;
|
||||
}
|
||||
if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
|
||||
@ -240,11 +254,13 @@ namespace WarmlyShip
|
||||
}
|
||||
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
|
||||
}
|
||||
|
||||
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
_logger.LogInformation("Осуществлён переход на карту под названием {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
}
|
||||
|
||||
private void ButtonDeleteMap_Click(object sender, EventArgs e)
|
||||
@ -257,6 +273,7 @@ namespace WarmlyShip
|
||||
{
|
||||
_mapsCollection.DelMap(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation("Удалена карта {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -271,12 +288,14 @@ namespace WarmlyShip
|
||||
try
|
||||
{
|
||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -287,17 +306,18 @@ namespace WarmlyShip
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
// TODO продумать логику
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
|
||||
ReloadMaps();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
|
||||
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace WarmlyShip
|
||||
{
|
||||
internal static class Program
|
||||
@ -8,7 +13,21 @@ namespace WarmlyShip
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormMapWithSetShip());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetShip>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetShip>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddNLog("nlog.config");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -37,17 +37,13 @@
|
||||
// Удаление объекта из набора с конкретной позиции
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < Count || position > 0)
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
if (_places.ElementAt(position) != null)
|
||||
{
|
||||
T ship = _places[position];
|
||||
_places.RemoveAt(position);
|
||||
return ship;
|
||||
}
|
||||
throw new ShipNotFoundException(position);
|
||||
}
|
||||
return null;
|
||||
T ship = _places[position];
|
||||
_places.RemoveAt(position);
|
||||
return ship;
|
||||
}
|
||||
// Получение объекта из набора по позиции
|
||||
public T this[int position]
|
||||
|
@ -8,6 +8,24 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="nlog.config" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
|
||||
<PackageReference Include="Serilog" Version="2.12.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
15
WarmlyShip/WarmlyShip/nlog.config
Normal file
15
WarmlyShip/WarmlyShip/nlog.config
Normal file
@ -0,0 +1,15 @@
|
||||
<?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="carlog-${shortdate}.log" />
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
Loading…
x
Reference in New Issue
Block a user