You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.2 KiB
80 lines
2.2 KiB
// Author: Gockner, Simon
|
|
// Created: 2019-09-26
|
|
// Copyright(c) 2019 SimonG. All Rights Reserved.
|
|
|
|
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Lib.Logging.Interfaces;
|
|
using Lib.Logging.Loggers.Interfaces;
|
|
|
|
namespace Lib.Logging.Loggers
|
|
{
|
|
/// <summary>
|
|
/// An <see cref="ILogger"/> that writes log messages to a set file
|
|
/// </summary>
|
|
public class FileLogger : IFileLogger
|
|
{
|
|
private readonly StreamWriter _fileWriter;
|
|
private readonly Timer _timer;
|
|
|
|
private readonly SemaphoreSlim _lockObject = new SemaphoreSlim(1);
|
|
|
|
/// <summary>
|
|
/// Constructor for <see cref="FileLogger"/>
|
|
/// </summary>
|
|
/// <param name="filePath">The directory of the LogFile</param>
|
|
/// <param name="fileName">The path of the LogFile</param>
|
|
public FileLogger(string filePath, string fileName)
|
|
{
|
|
Directory.CreateDirectory(filePath);
|
|
_fileWriter = new StreamWriter(Path.Combine(filePath, fileName), true);
|
|
_timer = new Timer(TimerCallback, null, 0, 1000);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Write the given <see cref="string"/> to the file
|
|
/// </summary>
|
|
/// <param name="message">The <see cref="ILogMessage"/></param>
|
|
public async Task Write(ILogMessage message)
|
|
{
|
|
await _lockObject.WaitAsync();
|
|
try
|
|
{
|
|
await _fileWriter.WriteAsync(message.ToString());
|
|
}
|
|
finally
|
|
{
|
|
_lockObject.Release();
|
|
}
|
|
}
|
|
|
|
private async void TimerCallback(object state) => await Flush();
|
|
|
|
private async Task Flush()
|
|
{
|
|
await _lockObject.WaitAsync();
|
|
try
|
|
{
|
|
await _fileWriter.FlushAsync();
|
|
}
|
|
finally
|
|
{
|
|
_lockObject.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="DisposeAsync"/> the <see cref="FileLogger"/>
|
|
/// </summary>
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _timer.DisposeAsync();
|
|
|
|
await Flush();
|
|
await _fileWriter.DisposeAsync();
|
|
|
|
_lockObject.Dispose();
|
|
}
|
|
}
|
|
} |