Логирование
This commit is contained in:
parent
58f9a4f809
commit
3a77f272fc
@ -8,6 +8,23 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="nlog.config" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="nlog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</EmbeddedResource>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||||
|
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
|
||||||
|
<PackageReference Include="Serilog" Version="2.12.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="Properties\Resources.Designer.cs">
|
<Compile Update="Properties\Resources.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using System;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
@ -24,9 +25,11 @@ namespace AirplaneWithRadar
|
|||||||
{"Карта туманного неба с грозой", new FoggySkyMap() }
|
{"Карта туманного неба с грозой", new FoggySkyMap() }
|
||||||
};
|
};
|
||||||
private readonly MapsCollection _mapsCollection;
|
private readonly MapsCollection _mapsCollection;
|
||||||
public FormMapWithSetAirplane()
|
private ILogger _logger;
|
||||||
|
public FormMapWithSetAirplane(ILogger<FormMapWithSetAirplane> 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 _mapDict)
|
foreach (var elem in _mapDict)
|
||||||
@ -94,19 +97,23 @@ namespace AirplaneWithRadar
|
|||||||
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1)
|
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект добавлен");
|
MessageBox.Show("Объект добавлен");
|
||||||
|
_logger.LogInformation("Добавлен объект {@Airplane}", airplane);
|
||||||
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не удалось добавить объект");
|
MessageBox.Show("Не удалось добавить объект");
|
||||||
|
_logger.LogInformation("Не удалось добавить объект");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (StorageOverflowException ex)
|
catch (StorageOverflowException ex)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
|
||||||
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
}
|
||||||
catch (ArgumentException ex)
|
catch (ArgumentException ex)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, airplane);
|
||||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -143,22 +150,27 @@ namespace AirplaneWithRadar
|
|||||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty] - pos != null)
|
var deletedAirplane = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||||
|
if (deletedAirplane != null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Объект удалён");
|
MessageBox.Show("Объект удалён");
|
||||||
|
_logger.LogInformation("Из текущей карты удалён объект {@Ship}", deletedAirplane);
|
||||||
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
|
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
|
||||||
MessageBox.Show("Не удалось удалить объект");
|
MessageBox.Show("Не удалось удалить объект");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (AirplaneNotFoundException ex)
|
catch (AirplaneNotFoundException ex)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
|
||||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
|
||||||
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -224,11 +236,13 @@ namespace AirplaneWithRadar
|
|||||||
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
|
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
|
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
|
||||||
{
|
{
|
||||||
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogInformation("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
|
if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
|
||||||
@ -238,11 +252,13 @@ namespace AirplaneWithRadar
|
|||||||
}
|
}
|
||||||
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
|
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
|
||||||
ReloadMaps();
|
ReloadMaps();
|
||||||
|
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
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)
|
private void ButtonDeleteMap_Click(object sender, EventArgs e)
|
||||||
@ -255,6 +271,7 @@ namespace AirplaneWithRadar
|
|||||||
{
|
{
|
||||||
_mapsCollection.DelMap(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
_mapsCollection.DelMap(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||||
ReloadMaps();
|
ReloadMaps();
|
||||||
|
_logger.LogInformation("Удалена карта {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -269,11 +286,13 @@ namespace AirplaneWithRadar
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||||
|
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
|
||||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -290,11 +309,13 @@ namespace AirplaneWithRadar
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||||
|
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
|
||||||
ReloadMaps();
|
ReloadMaps();
|
||||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
|
||||||
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
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 AirplaneWithRadar
|
namespace AirplaneWithRadar
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
@ -11,7 +16,21 @@ namespace AirplaneWithRadar
|
|||||||
// 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 FormMapWithSetAirplane());
|
var services = new ServiceCollection();
|
||||||
|
ConfigureServices(services);
|
||||||
|
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||||
|
{
|
||||||
|
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirplane>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static void ConfigureServices(ServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<FormMapWithSetAirplane>()
|
||||||
|
.AddLogging(option =>
|
||||||
|
{
|
||||||
|
option.SetMinimumLevel(LogLevel.Information);
|
||||||
|
option.AddNLog("nlog.config");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -37,17 +37,14 @@
|
|||||||
// Удаление объекта из набора с конкретной позиции
|
// Удаление объекта из набора с конкретной позиции
|
||||||
public T Remove(int position)
|
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 AirplaneNotFoundException(position);
|
throw new AirplaneNotFoundException(position);
|
||||||
}
|
}
|
||||||
return null;
|
T airplane = _places[position];
|
||||||
|
_places.RemoveAt(position);
|
||||||
|
return airplane;
|
||||||
|
|
||||||
}
|
}
|
||||||
// Получение объекта из набора по позиции
|
// Получение объекта из набора по позиции
|
||||||
public T this[int position]
|
public T this[int position]
|
||||||
|
15
AirplaneWithRadar/AirplaneWithRadar/nlog.config
Normal file
15
AirplaneWithRadar/AirplaneWithRadar/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