Files
BeWoPlaner/Service/Core/FileLogger.cs

57 lines
1.4 KiB
C#
Raw Normal View History

2025-06-10 14:29:34 +02:00
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.Exceptions;
using BS.Shared.Interface;
2025-06-13 11:37:19 +02:00
using Newtonsoft.Json;
2025-06-10 14:29:34 +02:00
using RestSharp.Validation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeWo.Service.Core
{
public class FileLogger
{
private readonly string _filePath;
private readonly LogLevel _minimumLevel;
private readonly object _lock = new object();
public FileLogger(string filePath, LogLevel minimumLevel = LogLevel.Debug)
{
if(filePath == null) throw new ArgumentNullException(nameof(filePath));
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
2025-06-10 14:29:34 +02:00
_filePath = filePath;
_minimumLevel = minimumLevel;
}
2025-06-13 11:37:19 +02:00
public void LogJson(LogLevel level, object json, string module = null)
{
var str = JsonConvert.SerializeObject(json, Formatting.Indented);
Log(level, str, module);
}
2025-06-10 14:29:34 +02:00
public void LogError(Exception exception, string module = null)
=> Log(LogLevel.Error, exception.ToString(), module);
public void Log(LogLevel level, string message, string module = null)
{
if (level < _minimumLevel)
return;
string timestamp = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss,ff");
string logEntry = $"[{timestamp}] [{level}] {module}: {message}";
lock (_lock)
{
File.AppendAllText(_filePath, logEntry + Environment.NewLine);
}
}
}
}