Skip to content

Commit

Permalink
added ILogger pattern to main downloader class
Browse files Browse the repository at this point in the history
  • Loading branch information
bezzad committed Dec 1, 2023
1 parent 088efd8 commit f3be41a
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 4 deletions.
122 changes: 122 additions & 0 deletions src/Downloader.Test/Helper/FileLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using Downloader.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Downloader.Test.Helper;

internal class FileLogger : ILogger, IDisposable
{
private volatile bool _disposed = false;
private SemaphoreSlim _semaphore = new SemaphoreSlim(0);
protected readonly ConcurrentQueue<string> LogQueue;
protected string LogPath;
protected StreamWriter LogStream;

public FileLogger(string logPath)
{
LogQueue = new ConcurrentQueue<string>();
LogPath = logPath;
LogStream = new StreamWriter(FileHelper.CreateFile(logPath));

Task<Task> task = Task.Factory.StartNew(
function: Writer,
cancellationToken: default,
creationOptions: TaskCreationOptions.LongRunning,
scheduler: TaskScheduler.Default);

task.Unwrap();
}

public void Debug(string message)
{
Log(nameof(Debug), message);
}

public void Info(string message)
{
Log(nameof(Info), message);
}

public void Warning(string message)
{
Log(nameof(Warning), message);
}

public void Warning(string message, Exception exception)
{
Log(nameof(Warning), message, exception);
}

public void Error(string message)
{
Log(nameof(Error), message);
}

public void Error(string message, Exception exception)
{
Log(nameof(Error), message, exception);
}

public void Fatal(string message)
{
Log(nameof(Fatal), message);
}

public void Fatal(string message, Exception exception)
{
Log(nameof(Fatal), message, exception);
}

protected void Log(string logType, string message, Exception exception = null)
{
if (!_disposed)
{
LogQueue.Enqueue(Formatter(logType, message, exception));
_semaphore.Release();
}
}

public virtual string Formatter(string logType, string message, Exception exception)
{
var log = $"{DateTime.Now:s} | {logType} | {message}";
if (exception is not null)
{
log += " | " + exception.Message + ": " + exception.StackTrace;
}

return log;
}

private async Task Writer()
{
while (!_disposed)
{
await _semaphore.WaitAsync().ConfigureAwait(false);
if (LogQueue.TryDequeue(out var log))
{
await LogStream.WriteLineAsync(log).ConfigureAwait(false);
}
}
}

public void Dispose()
{
_disposed = true;
LogQueue.Clear();
LogStream?.Dispose();
LogStream = null;
}

public async Task FlushAsync()
{
while (!_disposed && _semaphore.CurrentCount > 0)
{
await Task.Delay(100);
}

await (LogStream?.FlushAsync() ?? Task.CompletedTask).ConfigureAwait(false);
}
}
9 changes: 7 additions & 2 deletions src/Downloader/AbstractDownloadService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Downloader.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
Expand All @@ -12,6 +13,7 @@ namespace Downloader
{
public abstract class AbstractDownloadService : IDownloadService, IDisposable
{
protected ILogger _logger;
protected SemaphoreSlim _parallelSemaphore;
protected readonly SemaphoreSlim _singleInstanceSemaphore = new SemaphoreSlim(1, 1);
protected CancellationTokenSource _globalCancellationTokenSource;
Expand Down Expand Up @@ -206,8 +208,6 @@ protected void OnDownloadStarted(DownloadStartedEventArgs e)

protected void OnDownloadFileCompleted(AsyncCompletedEventArgs e)
{
// flush streams
Package.Flush();
Package.IsSaving = false;

if (e.Cancelled)
Expand Down Expand Up @@ -261,6 +261,11 @@ protected void OnChunkDownloadProgressChanged(object sender, DownloadProgressCha
DownloadProgressChanged?.Invoke(this, totalProgressArg);
}

public void AddLogger(ILogger logger)
{
_logger = logger;
}

public virtual void Dispose()
{
Clear().Wait();
Expand Down
18 changes: 18 additions & 0 deletions src/Downloader/Extensions/Logging/ILogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Threading.Tasks;

namespace Downloader.Extensions.Logging;

public interface ILogger
{
void Debug(string message);
void Info(string message);
void Warning(string message);
void Warning(string message, Exception exception);
void Error(string message);
void Error(string message, Exception exception);
void Fatal(string message);
void Fatal(string message, Exception exception);
string Formatter(string logType, string message, Exception exception);
Task FlushAsync();
}
4 changes: 2 additions & 2 deletions src/Downloader/FileHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ namespace Downloader
{
internal static class FileHelper
{
public static Stream CreateFile(string filename)
public static FileStream CreateFile(string filename)
{
string directory = Path.GetDirectoryName(filename);
if (string.IsNullOrWhiteSpace(directory))
{
return Stream.Null;
return null;
}

if (Directory.Exists(directory) == false)
Expand Down

0 comments on commit f3be41a

Please sign in to comment.