Skip to content

Commit

Permalink
Solution - Add and used Logger.
Browse files Browse the repository at this point in the history
  • Loading branch information
Stan-Kudri committed Oct 12, 2023
1 parent 97a8f97 commit 0043dc2
Show file tree
Hide file tree
Showing 9 changed files with 143 additions and 7 deletions.
35 changes: 35 additions & 0 deletions WatchList.Core/Logger/ConsoleLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.Extensions.Logging;

namespace WatchList.Core.Logger
{
public sealed class ConsoleLogger : ILogger
{
private LogLevel _logLevel;

Check warning on line 7 in WatchList.Core/Logger/ConsoleLogger.cs

View workflow job for this annotation

GitHub Actions / Lint

Make field readonly

public ConsoleLogger(LogLevel logLevel) => _logLevel = logLevel;

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}

var message = formatter(state, exception);
Console.WriteLine("[{0} {1:G}] {2}", logLevel, DateTime.Now, message);
}

public bool IsEnabled(LogLevel logLevel) => _logLevel <= logLevel;

public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
=> new Disposable();

private sealed class Disposable : IDisposable
{
public void Dispose()
{
}
}
}
}
48 changes: 48 additions & 0 deletions WatchList.Core/Logger/FileLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Globalization;
using Microsoft.Extensions.Logging;

namespace WatchList.Core.Logger
{
public class FileLogger : ILogger
{
private LogLevel _logLevel;

Check warning on line 8 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / Lint

Make field readonly
private readonly string _pathFileLog;

Check warning on line 9 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Readonly fields should appear before non-readonly fields (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md)

Check warning on line 9 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Readonly fields should appear before non-readonly fields (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md)

Check warning on line 9 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / Lint

Readonly fields should appear before non-readonly fields

Check warning on line 9 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Readonly fields should appear before non-readonly fields (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md)

Check warning on line 9 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Readonly fields should appear before non-readonly fields (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md)

public FileLogger(LogLevel logLevel, string pathFileLog)
{
_logLevel = logLevel;
_pathFileLog = pathFileLog;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}

var message = formatter(state, exception);
var logText = string.Format("[{0} {1:G}] {2}", logLevel, DateTime.Now, message);
File.AppendAllText(BuildPath(), logText + Environment.NewLine);
}

public bool IsEnabled(LogLevel logLevel) => _logLevel <= logLevel;

public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
=> new Disposable();

private sealed class Disposable : IDisposable
{
public void Dispose()
{
}
}

private string BuildPath()

Check warning on line 42 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 42 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 42 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / Lint

A method should not follow a class

Check warning on line 42 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 42 in WatchList.Core/Logger/FileLogger.cs

View workflow job for this annotation

GitHub Actions / build

{
var dateStr = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
return Path.Combine(_pathFileLog, dateStr + ".txt");
}
}
}
13 changes: 12 additions & 1 deletion WatchList.Core/Repository/WatchItemRepository.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using WatchList.Core.Model.ItemCinema;
using WatchList.Core.PageItem;
using WatchList.Core.Repository.Db;
Expand All @@ -9,8 +10,13 @@ namespace WatchList.Core.Repository
public class WatchItemRepository : IWatchItemRepository
{
private readonly WatchCinemaDbContext _db;
private readonly ILogger _logger;

public WatchItemRepository(WatchCinemaDbContext db) => _db = db;
public WatchItemRepository(WatchCinemaDbContext db, ILogger logger)
{
_db = db;
_logger = logger;
}

public PagedList<WatchItem> GetPage(WatchItemSearchRequest searchRequest)
{
Expand All @@ -24,6 +30,7 @@ public void Add(WatchItem item)
item.Id = _db.ReplaceIdIsNotFree(item);
_db.Add(item);
_db.SaveChanges();
_logger.LogInformation("Add item with ID {0}", item.Id);
}

public void Remove(Guid id)
Expand All @@ -33,6 +40,8 @@ public void Remove(Guid id)
{
throw new InvalidOperationException("Interaction element not found.");
}

_logger.LogInformation("Remove item with ID {0}", id);
}

public void Update(WatchItem editItem)
Expand All @@ -52,6 +61,8 @@ public void Update(WatchItem editItem)
item.Status = editItem.Status;

_db.SaveChanges();

_logger.LogInformation("Edit item with ID {0}", item.Id);
}

public List<Guid> SelectDuplicateItems(WatchItem item) =>
Expand Down
7 changes: 5 additions & 2 deletions WatchList.Core/Service/DataLoading/DownloadDataService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.Extensions.Logging;
using WatchList.Core.Model.Filter;
using WatchList.Core.Model.QuestionResult;
using WatchList.Core.Model.Sorting;
Expand All @@ -11,13 +12,14 @@ namespace WatchList.Core.Service.DataLoading
public class DownloadDataService
{
private readonly WatchItemRepository _repository;

private readonly IMessageBox _messageBox;
private readonly ILogger _logger;

public DownloadDataService(WatchItemRepository repository, IMessageBox messageBox, int numberOfItemPerPage = 500)
public DownloadDataService(WatchItemRepository repository, IMessageBox messageBox, ILogger logger, int numberOfItemPerPage = 500)
{
_repository = repository;
_messageBox = messageBox;
_logger = logger;
NumberOfItemPerPage = numberOfItemPerPage;
}

Expand All @@ -33,6 +35,7 @@ public void Download(WatchItemRepository repository, ILoadRule loadRule)
var watchItemCollection = new WatchItemCollection(pagedList);
watchItemCollection = loadRule.Apply(watchItemCollection);

_logger.LogInformation("Load items according to selected rules");
AddItems(watchItemCollection);
UpdateItems(watchItemCollection);

Expand Down
1 change: 1 addition & 0 deletions WatchList.Core/WatchList.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<PackageReference Include="Ardalis.SmartEnum.SystemTextJson" Version="2.1.0" />
<PackageReference Include="CassandraCSharpDriver" Version="3.18.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
1 change: 1 addition & 0 deletions WatchList.WinForms/BoxCinemaForm.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions WatchList.WinForms/BoxCinemaForm.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using MaterialSkin.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WatchList.Core.Model.Filter.Components;
using WatchList.Core.Model.ItemCinema;
using WatchList.Core.Model.ItemCinema.Components;
Expand Down Expand Up @@ -36,6 +37,7 @@ public partial class BoxCinemaForm : MaterialForm
private readonly WatchItemService _itemService;
private readonly IMessageBox _messageBox;
private readonly WatchItemRepository _itemRepository;
private readonly ILogger _logger;

private WatchItemSearchRequest _searchRequest = new WatchItemSearchRequest();

Expand All @@ -48,8 +50,8 @@ public BoxCinemaForm(IServiceProvider serviceProvider)
_itemRepository = serviceProvider.GetRequiredService<WatchItemRepository>();
_messageBox = serviceProvider.GetRequiredService<IMessageBox>();
_itemService = serviceProvider.GetRequiredService<WatchItemService>();
_logger = serviceProvider.GetRequiredService<ILogger>();
_pagedList = _itemService.GetPage(_searchRequest);

Load += BoxCinemaForm_Load;
}

Expand Down Expand Up @@ -95,6 +97,7 @@ private void BtnAddCinema_Click(object sender, EventArgs e)
return;
}

_logger.LogInformation("Click save add item");
var itemCinema = addForm.GetCinema();
_itemService.Add(itemCinema.ToWatchItem());

Expand All @@ -114,6 +117,7 @@ private void BtnEditRow_Click(object sender, EventArgs e)
return;
}

_logger.LogInformation("Click save edit item");
var updateItem = updateForm.GetEditItemCinema();
_itemService.Update(oldItem.ToWatchItem(), updateItem.ToWatchItem());
UpdateGridData();
Expand Down Expand Up @@ -141,6 +145,7 @@ private void BtnDeleteMovie_Click(object sender, EventArgs e)
return;
}

_logger.LogInformation("Click delite item");
foreach (var id in selectedRowIds)
{
RemoveItemRowGrid(id);
Expand All @@ -164,6 +169,7 @@ private void BtnDownloadDataFile_Click(object sender, EventArgs e)
return;
}

_logger.LogInformation("Add item from the selected file <{0}>", openReplaceDataFromFile.FileName);
var dbContext = new FileDbContextFactory(openReplaceDataFromFile.FileName).Create();
var loadRuleConfig = dataLoadingForm.GetLoadRuleConfig();
var loadRuleHasGrade = new DeleteGradeRule(loadRuleConfig);
Expand All @@ -172,13 +178,18 @@ private void BtnDownloadDataFile_Click(object sender, EventArgs e)
var loadDuplicateItem = new DuplicateLoadRule(_itemRepository, loadRuleConfig);
var aggregateRules = new AggregateLoadRule { loadRuleHasGrade, loadRuleType, loadRuleMoreGrade, loadDuplicateItem };

var repositoryDataDownload = new WatchItemRepository(dbContext);
var repositoryDataDownload = new WatchItemRepository(dbContext, _logger);

var downloadDataService = _serviceProvider.GetRequiredService<DownloadDataService>();
downloadDataService.Download(repositoryDataDownload, aggregateRules);
UpdateGridData();
}

private void BoxCinemaForm_FormClosed(object sender, FormClosedEventArgs e)
{
_logger.LogInformation("Close App.");
}

private void BtnBackPage_Click(object sender, EventArgs e)
{
if (_pagedList.HasPreviousPage)
Expand Down
29 changes: 27 additions & 2 deletions WatchList.WinForms/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using MaterialSkin;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WatchList.Core.Logger;
using WatchList.Core.Repository;
using WatchList.Core.Service;
using WatchList.Core.Service.Component;
Expand All @@ -23,6 +25,9 @@ public static void Main()
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();

var path = "logs";
CreatDirectoryIfNotExists(path);

var serviceCollection = new ServiceCollection()
.AddSingleton(new FileDbContextFactory("app.db"))
.AddScoped(e => e.GetRequiredService<FileDbContextFactory>().Create())
Expand All @@ -32,7 +37,9 @@ public static void Main()
.AddScoped<WatchItemService>()
.AddScoped<DownloadDataService>()
.AddTransient<MergeDatabaseForm>()
.AddTransient<BoxCinemaForm>();
.AddTransient<BoxCinemaForm>()
//.AddTransient<ILogger>(e => new ConsoleLogger(LogLevel.Information))

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / Lint

Single line comment should begin with a space.

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / Lint

Single-line comment should be preceded by blank line

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Check warning on line 41 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

.AddTransient<ILogger>(e => new FileLogger(LogLevel.Trace, path));

using var contain = serviceCollection.BuildServiceProvider(new ServiceProviderOptions
{
Expand All @@ -50,7 +57,25 @@ public static void Main()
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.Purple900, Primary.DeepPurple700, Primary.Purple50, Accent.LightBlue200, TextShade.WHITE);

Application.Run(form);
var loger = scope.ServiceProvider.GetRequiredService<ILogger>();

try
{
loger.LogTrace("Launch the application");
Application.Run(form);
}
catch (Exception ex)
{
loger.LogError(ex, "Unhandled exception");
}
}

static void CreatDirectoryIfNotExists(string path)

Check warning on line 73 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Element 'CreatDirectoryIfNotExists' should declare an access modifier (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1400.md)

Check warning on line 73 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / Lint

Element 'CreatDirectoryIfNotExists' should declare an access modifier

Check warning on line 73 in WatchList.WinForms/Program.cs

View workflow job for this annotation

GitHub Actions / build

Element 'CreatDirectoryIfNotExists' should declare an access modifier (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1400.md)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
}
}
1 change: 1 addition & 0 deletions WatchList.WinForms/WatchList.WinForms.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<PackageReference Include="Ardalis.SmartEnum.SystemTextJson" Version="2.1.0" />
<PackageReference Include="MaterialSkin.2" Version="2.3.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down

0 comments on commit 0043dc2

Please sign in to comment.