using BS.Shared; using BS.Shared.Core; using BS.Shared.Exceptions; using BS.Shared.Interface; using Newtonsoft.Json; 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))) throw new BeWoInvalidOperationException(AppError.LoggerPathDoNotExist); _filePath = filePath; _minimumLevel = minimumLevel; } public void LogJson(LogLevel level, object json, string module = null) { var str = JsonConvert.SerializeObject(json, Formatting.Indented); Log(level, str, module); } 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); } } } }