83 lines
2.3 KiB
C#
83 lines
2.3 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
using Newtonsoft.Json;
|
|
using System.Threading;
|
|
using xCommons.Extensions;
|
|
using xExceptions.Constants;
|
|
using System.Threading.Tasks;
|
|
using xLoggingService.Models;
|
|
using xCommons.Configurations;
|
|
using xLoggingService.Interfaces;
|
|
using xLoggingService.Configuration;
|
|
using xLoggingService.Extensions;
|
|
|
|
namespace xLoggingService.Writers
|
|
{
|
|
public sealed class XFileLogWriter : IXLogWriter
|
|
{
|
|
//
|
|
private readonly object sync = new();
|
|
private readonly XAppConfiguration appConfiguration;
|
|
private readonly XLoggingServiceConfiguration configuration;
|
|
|
|
public XFileLogWriter(
|
|
XAppConfiguration appConfiguration,
|
|
XLoggingServiceConfiguration configuration
|
|
)
|
|
{
|
|
//
|
|
if (configuration.IsNull() || appConfiguration.IsNull())
|
|
{
|
|
XException.InvalidConfiguration.Throw();
|
|
}
|
|
|
|
//
|
|
this.configuration = configuration;
|
|
this.appConfiguration = appConfiguration;
|
|
|
|
//
|
|
Directory.CreateDirectory(configuration.File.Directory);
|
|
}
|
|
|
|
public Task WriteAsync(
|
|
XLogEntry entry,
|
|
CancellationToken token
|
|
)
|
|
{
|
|
//
|
|
if (entry.IsNull())
|
|
{
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
//
|
|
// Handle Task Enrichment ...
|
|
entry = entry.Enrich(appConfiguration);
|
|
|
|
//
|
|
if (entry.Level < configuration.File.MinimumLevel)
|
|
{
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
//
|
|
var path = Path.Combine(configuration.File.Directory, configuration.File.FileName.Replace("-", "-"));
|
|
|
|
//
|
|
lock (sync)
|
|
{
|
|
//
|
|
File.AppendAllText(path, configuration.File.Format.Equals(
|
|
"Json",
|
|
StringComparison.OrdinalIgnoreCase)
|
|
? JsonConvert.SerializeObject(entry) + Environment.NewLine
|
|
: $"{entry.Timestamp:O} [{entry.Level}] {entry.Category}: {entry.Message}{Environment.NewLine}", Encoding.UTF8);
|
|
}
|
|
|
|
//
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|