namespace VideoBrowser.Common
{
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using System;
using System.IO;
using System.Reflection;
///
/// Defines the
/// Log the important process to trace the last processes before error occurs.
///
public static class Logger
{
#region Constructors
///
/// Initializes static members of the class.
///
static Logger()
{
Setup(nameof(VideoBrowser));
}
#endregion Constructors
#region Properties
///
/// Gets the Log.
///
public static ILog Log { get; } = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
///
/// Gets the LogFilePath.
///
public static string LogFilePath { get; private set; }
#endregion Properties
#region Methods
///
/// The Debug Log.
///
/// The message.
public static void Debug(object message)
{
Log.Debug(message);
}
///
/// The Error Log.
///
/// The message.
public static void Error(object message)
{
Log.Error(message);
}
///
/// The Fatal Log.
///
/// The message.
public static void Fatal(object message)
{
Log.Fatal(message);
}
///
/// The Info.
///
/// The message.
public static void Info(object message = null)
{
if (message == null)
{
message = string.Empty;
}
Log.Info(message);
System.Diagnostics.Trace.WriteLine(message);
}
///
/// The Info Log.
///
/// The source.
/// The message.
public static void Info(this object source, object message)
{
Log.Info(message);
}
///
/// The Setup.
///
/// The appName.
public static void Setup(string appName)
{
LogFilePath = GetLogFilePath(appName);
var entryAssembly = Assembly.GetExecutingAssembly();
var hierarchy = (Hierarchy)LogManager.GetRepository(entryAssembly);
var patternLayout = new PatternLayout
{
ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"
};
patternLayout.ActivateOptions();
var roller = new RollingFileAppender
{
AppendToFile = false,
File = LogFilePath,
Layout = patternLayout,
MaxSizeRollBackups = 5,
MaximumFileSize = "1GB",
RollingStyle = RollingFileAppender.RollingMode.Size,
StaticLogFileName = true
};
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
var memory = new MemoryAppender();
memory.ActivateOptions();
hierarchy.Root.AddAppender(memory);
hierarchy.Root.Level = Level.Info;
hierarchy.Configured = true;
}
///
/// The Warn.
///
/// The source.
/// The message.
public static void Warn(this object source, object message)
{
Log.Warn(message);
}
///
/// Saves given Exception's stack trace to a readable file in the local application data folder.
///
/// The Exception to save.
public static void WriteException(Exception ex)
{
Logger.Info(ex.ToString());
}
///
/// The GetLogFilePath.
///
/// The appName.
/// The .
internal static string GetLogFilePath(string appName)
{
var folder = AppEnvironment.GetUserLocalApplicationData();
var path = Path.Combine(folder, $"{appName}.log");
return path;
}
#endregion Methods
}
}