using Serilog; using Serilog.Configuration; using Serilog.Formatting.Json; using System; using System.Collections.Generic; using System.IO; namespace TINK.Model.Logging { /// Holds new logging levels. public enum RollingInterval { /// Create a new log file for each session (start of app). Session, } /// Provides logging file name helper functionality. public static class LoggerConfigurationHelper { /// Holds the log file name. private static ILoggingDirectoryManager DirectoryManager { get; set; } = new EmptyDirectoryLoggingManger(); /// Sets up logging to file. /// Object to set up logging with. /// Object to get file informaton from. /// Specifies rolling type. /// Count of file being retained. /// Logger object. public static LoggerConfiguration File( this LoggerSinkConfiguration loggerConfiguration, string logFileFolder, RollingInterval rollingInterval = RollingInterval.Session, int retainedFilesCountLimit = 10) { if (DirectoryManager is EmptyDirectoryLoggingManger) { // Roll file only once per app session. try { DirectoryManager = new LoggingDirectoryManager( Directory.GetFiles, Directory.Exists, (path) => Directory.CreateDirectory(path), System.IO.File.Delete, logFileFolder, Path.DirectorySeparatorChar, retainedFilesCountLimit); } catch (Exception l_oException) { Log.Error("Log directory manager could not be instanciated successfully. {@l_oException}", l_oException); DirectoryManager = new EmptyDirectoryLoggingManger(); } } try { DirectoryManager.DeleteObsoleteLogs(); } catch (Exception l_oException) { Log.Error("Not all obsolte log files could be deleted successfully. {@l_oException}", l_oException); } if (loggerConfiguration == null) { return null; } return loggerConfiguration.File( new JsonFormatter(), DirectoryManager.LogFileName, /*shared: true, // Leads to exception if activated.*/ rollingInterval: Serilog.RollingInterval.Infinite, retainedFileCountLimit: retainedFilesCountLimit); } /// Gets all log files in logging directory. /// /// List of log files. public static IList GetLogFiles(this ILogger p_oLogger) { try { return DirectoryManager.GetLogFiles(); } catch (Exception l_oException) { Log.Error("Getting list of log files failed. Empty list is returned instead. {@l_oException}", l_oException); return new List(); } } /// Gets path where log files are located. /// /// List of log files. public static string GetLogFilePath( this ILogger p_oLogger) { return DirectoryManager.LogFilePath; } } }