using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EFCDesk.Classes { public class ProcessLogger { private readonly string _logDirectory; private readonly long _maxFileSizeBytes; private readonly object _lock = new object(); private DateTime _currentLogDate; private string _currentLogFilePath; public ProcessLogger(string logDirectory = "Logs", string? logFileName = null, long maxFileSizeBytes = 1 * 1024 * 1024) // 1 MB { _logDirectory = logDirectory; _maxFileSizeBytes = maxFileSizeBytes; _currentLogDate = DateTime.Now; if (!Directory.Exists(_logDirectory)) { Directory.CreateDirectory(_logDirectory); } _currentLogFilePath = GetLogFilePath(_currentLogDate, logFileName); } public void LogInfo(string message) => Log("INFO", message); public void LogWarning(string message) => Log("WARNING", message); public void LogError(string message, Exception? ex = null) { string fullMessage = message; if (ex != null) { fullMessage += $"{Environment.NewLine}Exception: {ex.Message}{Environment.NewLine}StackTrace: {ex.StackTrace}"; } Log("ERROR", fullMessage); } private void Log(string level, string message) { string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}"; lock (_lock) { RotateLogFileIfNeeded(); File.AppendAllText(_currentLogFilePath, logEntry + Environment.NewLine); } } private void RotateLogFileIfNeeded() { DateTime now = DateTime.Now; // Cambio de día: nuevo archivo if (now.Date != _currentLogDate.Date) { _currentLogDate = now; _currentLogFilePath = GetLogFilePath(_currentLogDate); return; } // Excede tamaño máximo: crear nuevo archivo con sufijo incremental if (File.Exists(_currentLogFilePath) && new FileInfo(_currentLogFilePath).Length >= _maxFileSizeBytes) { int index = 1; string newPath; do { newPath = GetLogFilePath(_currentLogDate, null, index++); } while (File.Exists(newPath)); _currentLogFilePath = newPath; } } private string GetLogFilePath(DateTime date, string? customName = null, int index = 0) { string datePart = date.ToString("yyyyMMdd"); string baseName = string.IsNullOrWhiteSpace(customName) ? $"log_{datePart}" : Path.GetFileNameWithoutExtension(customName); string extension = ".txt"; string fileName = index == 0 ? $"{baseName}{extension}" : $"{baseName}_{index}{extension}"; return Path.Combine(_logDirectory, fileName); } } }