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 m_oDirectoryManager = 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 p_oLoggerConfiguration,
string p_strLogFileFolder,
RollingInterval p_oRollingInterval = RollingInterval.Session,
int p_iRetainedFilesCountLimit = 10)
{
if (m_oDirectoryManager is EmptyDirectoryLoggingManger)
{
// Roll file only once per app session.
try
{
m_oDirectoryManager = new LoggingDirectoryManager(
Directory.GetFiles,
Directory.Exists,
(path) => Directory.CreateDirectory(path),
System.IO.File.Delete,
p_strLogFileFolder,
Path.DirectorySeparatorChar,
p_iRetainedFilesCountLimit);
}
catch (Exception l_oException)
{
Log.Error("Log directory manager could not be instanciated successfully. {@l_oException}", l_oException);
m_oDirectoryManager = new EmptyDirectoryLoggingManger();
}
}
try
{
m_oDirectoryManager.DeleteObsoleteLogs();
}
catch (Exception l_oException)
{
Log.Error("Not all obsolte log files could be deleted successfully. {@l_oException}", l_oException);
}
if (p_oLoggerConfiguration == null)
{
return null;
}
return p_oLoggerConfiguration.File(
new JsonFormatter(),
m_oDirectoryManager.LogFileName,
/*shared: true, // Leads to exception if activated.*/
rollingInterval: Serilog.RollingInterval.Infinite,
retainedFileCountLimit: p_iRetainedFilesCountLimit);
}
/// Gets all log files in logging directory.
///
/// List of log files.
public static IList GetLogFiles(this ILogger p_oLogger)
{
try
{
return m_oDirectoryManager.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 m_oDirectoryManager.LogFilePath;
}
}
}