From 35fe3bf27ef7784b286c67d6be625bf25968e9e1 Mon Sep 17 00:00:00 2001 From: Geo7312 Date: Mon, 13 May 2024 00:31:00 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=207=20(=D0=BD=D0=B5=20=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 55 ++++++----- .../MassiveGenericObjects.cs | 36 ++++--- .../StorageCollection.cs | 33 ++++--- .../Drawnings/DrawningTrolleybus.cs | 2 +- .../Exceptions/CollectionOverflowException.cs | 17 ++++ .../Exceptions/ObjectNotFoundException.cs | 17 ++++ .../PositionOutOfCollectionException.cs | 14 +++ .../FormTrolleyBCollection.cs | 97 +++++++++++++------ .../ProjectTrolleybus/Program.cs | 24 ++++- .../ProjectTrolleybus.csproj | 11 +++ .../ProjectTrolleybus/nlog.config | 15 +++ 11 files changed, 237 insertions(+), 84 deletions(-) create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectTrolleybus/ProjectTrolleybus/nlog.config diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs index 8c54936..3901045 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ namespace ProjectTrolleybus.CollectionGenericObjects; +using ProjectTrolleybus.Exceptions; /// /// Параметризированный набор объектов @@ -33,44 +34,54 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - return null; + // проверка позиции + // выброс ошибки, если выход за границы списка + if (position < 0 || position > _maxCount) throw new PositionOutOfCollectionException(position); + + return _collection[position]; + } public int Insert(T obj) { - if (Count <= _maxCount) + // проверка, что не превышено максимальное количество элементов + if (_collection.Count >= _maxCount) { - _collection.Add(obj); - return Count; + throw new CollectionOverflowException(_maxCount); } - return -1; + // вставка в конец набора + _collection.Add(obj); + return _maxCount; } + public int Insert(T obj, int position) { - if (Count < _maxCount && position >= 0 && position < _maxCount) - { - _collection.Insert(position, obj); - return position; - } - return -1; + // проверка, что не превышено максимальное количество элементов + if (Count >= _maxCount) + throw new CollectionOverflowException(_maxCount); + + // проверка позиции + if (position < 0 || position >= _maxCount) + throw new PositionOutOfCollectionException(position); + + // вставка по позиции + _collection.Insert(position, obj); + return position; } - public T Remove(int position) + + public T? Remove(int position) { + // проверка позиции + if (position < 0 || position > _maxCount) throw new PositionOutOfCollectionException(position); + // удаление объекта из списка T temp = _collection[position]; - if (position >= 0 && position < _maxCount) - { - _collection.RemoveAt(position); - return temp; - } - return null; + _collection[position] = null; + return temp; } + public IEnumerable GetItems() { for (int i = 0; i < _collection.Count; i++) diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs index 944ded4..40b155d 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ namespace ProjectTrolleybus.CollectionGenericObjects; +using ProjectTrolleybus.Exceptions; /// /// Параметризированный набор объектов @@ -51,17 +52,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - // TODO проверка позиции + // проверка позиции if (position >= _collection.Length || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); } return _collection[position]; } + public int Insert(T obj) { - // TODO вставка в свободное место набора + // вставка в свободное место набора int index = 0; while (index < _collection.Length) { @@ -72,20 +74,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects } index++; } - return -1; + throw new CollectionOverflowException(Count); } + public int Insert(T obj, int position) { - // TODO проверка позиции - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда - // если нет после, ищем до - // TODO вставка + // проверка позиции if (position >= _collection.Length || position < 0) - return -1; + throw new PositionOutOfCollectionException(position); - // TODO проверка, что элемент массива по этой позиции пустой, если нет, то + // проверка, что элемент массива по этой позиции пустой, если нет, то if (_collection[position] != null) { // проверка, что после вставляемого элемента в массиве есть пустой элемент @@ -110,25 +109,32 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[j + 1] = _collection[j]; j--; } + throw new CollectionOverflowException(Count); } - // TODO вставка по позиции + // вставка по позиции _collection[position] = obj; return position; } + public T? Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из массива, присвоив элементу массива значение null + // проверка позиции + // удаление объекта из массива, присвоив элементу массива значение null if (position >= _collection.Length || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); } T temp = _collection[position]; _collection[position] = null; return temp; } + public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; i++) diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs index c96f572..b47e772 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,5 @@ using ProjectTrolleybus.Drawnings; -using System.Text; +using ProjectTrolleybus.Exceptions; namespace ProjectTrolleybus.CollectionGenericObjects; @@ -93,11 +93,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -105,7 +105,6 @@ public class StorageCollection File.Delete(filename); } - using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); @@ -138,19 +137,19 @@ public class StorageCollection } } } - return true; } + /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader reader = File.OpenText(filename)) @@ -159,13 +158,12 @@ public class StorageCollection if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - //если нет такой записи, то это не те данные - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); @@ -182,7 +180,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -192,9 +190,16 @@ public class StorageCollection { if (elem?.CreateDrawningTrolleyB() is T trolleyB) { - if (collection.Insert(trolleyB) == -1) + try { - return false; + if (collection.Insert(trolleyB) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } @@ -202,9 +207,9 @@ public class StorageCollection _storages.Add(record[0], collection); } } - return true; } + /// /// Создание коллекции по типу /// diff --git a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs index 595f30d..dddb33b 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Drawnings/DrawningTrolleybus.cs @@ -26,7 +26,7 @@ public class DrawningTrolleybus : DrawningTrolleyB /// Конструктор, принимающий объект EntityTrolleyB в качестве параметра /// /// - public DrawningTrolleybus(EntityTrolleybus exc) : base(150, 80) + public DrawningTrolleybus(EntityTrolleybus exc) : base(120, 80) { EntityTrolleyB = new EntityTrolleybus(exc.Speed, exc.Weight, exc.BodyColor, exc.AdditionalColor, exc.BatteryCompartment, exc.Horns); } diff --git a/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionOverflowException.cs b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..8fccfb7 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + +namespace ProjectTrolleybus.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} + diff --git a/ProjectTrolleybus/ProjectTrolleybus/Exceptions/ObjectNotFoundException.cs b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..5569e04 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + +namespace ProjectTrolleybus.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} + diff --git a/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..cbc806a --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectTrolleybus.Exceptions; + +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} + diff --git a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs index 38b8704..09f0bf9 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/FormTrolleyBCollection.cs @@ -1,5 +1,7 @@ -using ProjectTrolleybus.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectTrolleybus.CollectionGenericObjects; using ProjectTrolleybus.Drawnings; +using ProjectTrolleybus.Exceptions; using System.Windows.Forms; namespace ProjectTrolleybus; @@ -16,13 +18,20 @@ public partial class FormTrolleyBCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + + /// /// Конструктор /// - public FormTrolleyBCollection() + public FormTrolleyBCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -58,14 +67,19 @@ public partial class FormTrolleyBCollection : Form return; } - if (_company + trolleyB != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + trolleyB != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: {object}", trolleyB.GetDataForSave()); + } } - else + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -89,14 +103,19 @@ public partial class FormTrolleyBCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удалён"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } } - else + catch (ObjectNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -115,26 +134,35 @@ public partial class FormTrolleyBCollection : Form DrawningTrolleyB? trolleyB = null; int counter = 100; - while (trolleyB == null) + try { trolleyB = _company.GetRandomObject(); counter--; - if (counter <= 0) + while (trolleyB == null) { - break; + trolleyB = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } - } - if (trolleyB == null) - { - return; - } + if (trolleyB == null) + { + return; + } - FormTrolleybus form = new() + FormTrolleybus form = new() + { + SetTrolleyB = trolleyB + }; + form.ShowDialog(); + } + catch (Exception ex) { - SetTrolleyB = trolleyB, - }; - form.ShowDialog(); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } /// @@ -177,6 +205,7 @@ public partial class FormTrolleyBCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RerfreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция: {collectionName} типа: {collectionType}", textBoxCollectionName.Text, collectionType); } /// @@ -197,6 +226,7 @@ public partial class FormTrolleyBCollection : Form } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); + _logger.LogInformation("Удалена коллекция: {collectionName} ", textBoxCollectionName.Text); } @@ -256,13 +286,16 @@ public partial class FormTrolleyBCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -276,15 +309,17 @@ public partial class FormTrolleyBCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/Program.cs b/ProjectTrolleybus/ProjectTrolleybus/Program.cs index bfe6ed4..4027b76 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Program.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Program.cs @@ -1,4 +1,10 @@ + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace ProjectTrolleybus + { internal static class Program { @@ -11,7 +17,23 @@ namespace ProjectTrolleybus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTrolleyBCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj b/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj index af03d74..5f546b7 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj +++ b/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectTrolleybus/ProjectTrolleybus/nlog.config b/ProjectTrolleybus/ProjectTrolleybus/nlog.config new file mode 100644 index 0000000..8536c3a --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 62144f860d801ee8d47bc4cfb899ea19c33ca8cc Mon Sep 17 00:00:00 2001 From: Geo7312 Date: Mon, 13 May 2024 01:31:08 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=E2=84=96=206?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionGenericObjects/AbstractCompany.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs index e61a6fa..c067004 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/CollectionGenericObjects/AbstractCompany.cs @@ -33,7 +33,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального кол-ва объектов которое можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight) + 4; /// /// Конструктор -- 2.25.1 From b07df91eed458548083685e5c10bf31628141101 Mon Sep 17 00:00:00 2001 From: Geo7312 Date: Fri, 7 Jun 2024 17:01:37 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectTrolleybus/ProjectTrolleybus/Program.cs | 18 +++++++++++++++--- .../ProjectTrolleybus/ProjectTrolleybus.csproj | 8 ++++++++ .../ProjectTrolleybus/serilog.json | 15 +++++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 ProjectTrolleybus/ProjectTrolleybus/serilog.json diff --git a/ProjectTrolleybus/ProjectTrolleybus/Program.cs b/ProjectTrolleybus/ProjectTrolleybus/Program.cs index 4027b76..b2dec97 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/Program.cs +++ b/ProjectTrolleybus/ProjectTrolleybus/Program.cs @@ -1,7 +1,8 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; +using Serilog; namespace ProjectTrolleybus @@ -29,10 +30,21 @@ namespace ProjectTrolleybus /// private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton().AddLogging(option => + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); }); } } diff --git a/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj b/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj index 5f546b7..349d6dd 100644 --- a/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj +++ b/ProjectTrolleybus/ProjectTrolleybus/ProjectTrolleybus.csproj @@ -9,8 +9,16 @@ + + + + + + + + diff --git a/ProjectTrolleybus/ProjectTrolleybus/serilog.json b/ProjectTrolleybus/ProjectTrolleybus/serilog.json new file mode 100644 index 0000000..21a6582 --- /dev/null +++ b/ProjectTrolleybus/ProjectTrolleybus/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1