38 lines
1.2 KiB
C#
38 lines
1.2 KiB
C#
|
|
using System.IO;
|
||
|
|
using CloudPrint.Client.Models;
|
||
|
|
using CloudPrint.Client.Services.Abstractions;
|
||
|
|
|
||
|
|
namespace CloudPrint.Client.Services;
|
||
|
|
|
||
|
|
public sealed class FileAppLogger : IAppLogger
|
||
|
|
{
|
||
|
|
private readonly object _syncRoot = new();
|
||
|
|
|
||
|
|
public FileAppLogger()
|
||
|
|
{
|
||
|
|
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
||
|
|
LogDirectory = Path.Combine(appData, "CloudPrint.Client", "logs");
|
||
|
|
}
|
||
|
|
|
||
|
|
public string LogDirectory { get; }
|
||
|
|
|
||
|
|
public void Write(AppLogEntry entry)
|
||
|
|
{
|
||
|
|
ArgumentNullException.ThrowIfNull(entry);
|
||
|
|
Directory.CreateDirectory(LogDirectory);
|
||
|
|
|
||
|
|
var logPath = Path.Combine(LogDirectory, $"cloudprint-{DateTime.Now:yyyyMMdd}.log");
|
||
|
|
lock (_syncRoot)
|
||
|
|
{
|
||
|
|
File.AppendAllText(logPath, Format(entry) + Environment.NewLine);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string Format(AppLogEntry entry)
|
||
|
|
{
|
||
|
|
var exceptionText = string.IsNullOrWhiteSpace(entry.ExceptionText)
|
||
|
|
? string.Empty
|
||
|
|
: $" | Exception={entry.ExceptionText}";
|
||
|
|
return $"{entry.Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{entry.LevelText}] {entry.Message}{exceptionText}";
|
||
|
|
}
|
||
|
|
}
|