LoggingUtility
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using log4net;
using log4net.Core;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using log4net.Repository;
namespace Logging
{
public static class LoggingUtility
{
private static BufferingAppenderSkeleton[] bufferingAppendersCache = LoadAllBufferingAppenders();
public static void Flush(this ILog log)
{
foreach (BufferingAppenderSkeleton appender in bufferingAppendersCache)
{
appender.Flush();
}
}
private static BufferingAppenderSkeleton[] LoadAllBufferingAppenders()
{
List<BufferingAppenderSkeleton> bufferingAppenderList = new List<BufferingAppenderSkeleton>();
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
BufferingAppenderSkeleton bufferingAppender = appender as BufferingAppenderSkeleton;
if (bufferingAppender != null)
{
bufferingAppenderList.Add(bufferingAppender);
}
}
return bufferingAppenderList.ToArray();
}
public static Level GetLoggingLevel()
{
Hierarchy h = (Hierarchy)LogManager.GetRepository();
return h.Root.Level;
}
public static void SetLoggingLevel(Level level)
{
string strLogLevel = level.ToString();
ILoggerRepository[] repositories = LogManager.GetAllRepositories();
//Configure all loggers to be at the debug level.
foreach (log4net.Repository.ILoggerRepository repository in repositories)
{
repository.Threshold = repository.LevelMap[strLogLevel];
Hierarchy hier = (Hierarchy)repository;
ILogger[] loggers = hier.GetCurrentLoggers();
foreach (ILogger logger in loggers)
{
((Logger)logger).Level = hier.LevelMap[strLogLevel];
}
}
//Configure the root logger.
Hierarchy h = (Hierarchy)log4net.LogManager.GetRepository();
Logger rootLogger = h.Root;
rootLogger.Level = h.LevelMap[strLogLevel];
}
/// <summary>
/// Logs the runtime environment on application starts.
/// </summary>
/// <param name="logger"></param>
/// <param name="currentMethod"></param>
public static void LogAppStart(this ILog logger, MethodBase currentMethod)
{
#region -----------------------------INFO Environment --------------------------------------
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - Application Starts at : {1}",
currentMethod,
DateTime.Now);
logger.InfoFormat("###### {0} - Current Logging Level : {1}",
currentMethod,
LoggingUtility.GetLoggingLevel());
logger.InfoFormat("###### {0} - Environment : \r\n{1}",
currentMethod,
GetEnvironmentInfo());
}
#endregion --------------------------INFO Environment --------------------------------------
LogAssemblies(logger, currentMethod);
}
/// <summary>
/// Logs the timestamp on application ends.
/// </summary>
/// <param name="logger"></param>
/// <param name="currentMethod"></param>
public static void LogAppEnd(this ILog logger, MethodBase currentMethod)
{
#region -----------------------------INFO Exit --------------------------------------
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - Application Exits at : {1}",
currentMethod,
DateTime.Now);
logger.InfoFormat("\r\n\r\n");
}
#endregion --------------------------INFO Exit --------------------------------------
}
/// <summary>
/// Returns a string which holds the system information, such as OS version, CLR version
/// </summary>
/// <returns></returns>
private static string GetEnvironmentInfo()
{
StringBuilder sbuf = new StringBuilder();
sbuf.AppendLine("OS : " + Environment.OSVersion);
sbuf.AppendLine("CLR Version : " + Environment.Version.ToString());
sbuf.AppendLine("MachineName : " + Environment.MachineName);
sbuf.AppendLine("SystemDirectory : " + Environment.SystemDirectory);
sbuf.AppendLine("UserDomainName : " + Environment.UserDomainName);
sbuf.AppendLine("UserName : " + Environment.UserName);
sbuf.Append("CurrentDirectory : " + Environment.CurrentDirectory);
return sbuf.ToString();
}
/// <summary>
/// Logs all the assemblies already loaded, and also creates a log entry when a new assembly is loaded.
/// </summary>
/// <param name="logger"></param>
/// <param name="currentMethod"></param>
private static void LogAssemblies(ILog logger, MethodBase currentMethod)
{
// for future assemblies
AppDomain.CurrentDomain.AssemblyLoad += delegate(object sender, AssemblyLoadEventArgs args)
{
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - ************** Assemly Loaded : {1}",
MethodBase.GetCurrentMethod(),
args.LoadedAssembly.FullName);
logger.InfoFormat("###### {0} - ************** Assemly CodeBase : {1}",
MethodBase.GetCurrentMethod(),
args.LoadedAssembly.CodeBase);
}
};
// assemblies already loaded
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in assemblies)
{
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - ************** Assemly PreLoaded : {1}",
currentMethod,
asm.FullName);
logger.InfoFormat("###### {0} - ************** Assemly CodeBase : {1}",
currentMethod,
asm.CodeBase);
}
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using log4net;
using log4net.Core;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using log4net.Repository;
namespace Logging
{
public static class LoggingUtility
{
private static BufferingAppenderSkeleton[] bufferingAppendersCache = LoadAllBufferingAppenders();
public static void Flush(this ILog log)
{
foreach (BufferingAppenderSkeleton appender in bufferingAppendersCache)
{
appender.Flush();
}
}
private static BufferingAppenderSkeleton[] LoadAllBufferingAppenders()
{
List<BufferingAppenderSkeleton> bufferingAppenderList = new List<BufferingAppenderSkeleton>();
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
BufferingAppenderSkeleton bufferingAppender = appender as BufferingAppenderSkeleton;
if (bufferingAppender != null)
{
bufferingAppenderList.Add(bufferingAppender);
}
}
return bufferingAppenderList.ToArray();
}
public static Level GetLoggingLevel()
{
Hierarchy h = (Hierarchy)LogManager.GetRepository();
return h.Root.Level;
}
public static void SetLoggingLevel(Level level)
{
string strLogLevel = level.ToString();
ILoggerRepository[] repositories = LogManager.GetAllRepositories();
//Configure all loggers to be at the debug level.
foreach (log4net.Repository.ILoggerRepository repository in repositories)
{
repository.Threshold = repository.LevelMap[strLogLevel];
Hierarchy hier = (Hierarchy)repository;
ILogger[] loggers = hier.GetCurrentLoggers();
foreach (ILogger logger in loggers)
{
((Logger)logger).Level = hier.LevelMap[strLogLevel];
}
}
//Configure the root logger.
Hierarchy h = (Hierarchy)log4net.LogManager.GetRepository();
Logger rootLogger = h.Root;
rootLogger.Level = h.LevelMap[strLogLevel];
}
/// <summary>
/// Logs the runtime environment on application starts.
/// </summary>
/// <param name="logger"></param>
/// <param name="currentMethod"></param>
public static void LogAppStart(this ILog logger, MethodBase currentMethod)
{
#region -----------------------------INFO Environment --------------------------------------
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - Application Starts at : {1}",
currentMethod,
DateTime.Now);
logger.InfoFormat("###### {0} - Current Logging Level : {1}",
currentMethod,
LoggingUtility.GetLoggingLevel());
logger.InfoFormat("###### {0} - Environment : \r\n{1}",
currentMethod,
GetEnvironmentInfo());
}
#endregion --------------------------INFO Environment --------------------------------------
LogAssemblies(logger, currentMethod);
}
/// <summary>
/// Logs the timestamp on application ends.
/// </summary>
/// <param name="logger"></param>
/// <param name="currentMethod"></param>
public static void LogAppEnd(this ILog logger, MethodBase currentMethod)
{
#region -----------------------------INFO Exit --------------------------------------
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - Application Exits at : {1}",
currentMethod,
DateTime.Now);
logger.InfoFormat("\r\n\r\n");
}
#endregion --------------------------INFO Exit --------------------------------------
}
/// <summary>
/// Returns a string which holds the system information, such as OS version, CLR version
/// </summary>
/// <returns></returns>
private static string GetEnvironmentInfo()
{
StringBuilder sbuf = new StringBuilder();
sbuf.AppendLine("OS : " + Environment.OSVersion);
sbuf.AppendLine("CLR Version : " + Environment.Version.ToString());
sbuf.AppendLine("MachineName : " + Environment.MachineName);
sbuf.AppendLine("SystemDirectory : " + Environment.SystemDirectory);
sbuf.AppendLine("UserDomainName : " + Environment.UserDomainName);
sbuf.AppendLine("UserName : " + Environment.UserName);
sbuf.Append("CurrentDirectory : " + Environment.CurrentDirectory);
return sbuf.ToString();
}
/// <summary>
/// Logs all the assemblies already loaded, and also creates a log entry when a new assembly is loaded.
/// </summary>
/// <param name="logger"></param>
/// <param name="currentMethod"></param>
private static void LogAssemblies(ILog logger, MethodBase currentMethod)
{
// for future assemblies
AppDomain.CurrentDomain.AssemblyLoad += delegate(object sender, AssemblyLoadEventArgs args)
{
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - ************** Assemly Loaded : {1}",
MethodBase.GetCurrentMethod(),
args.LoadedAssembly.FullName);
logger.InfoFormat("###### {0} - ************** Assemly CodeBase : {1}",
MethodBase.GetCurrentMethod(),
args.LoadedAssembly.CodeBase);
}
};
// assemblies already loaded
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in assemblies)
{
if (logger.IsInfoEnabled)
{
logger.InfoFormat("###### {0} - ************** Assemly PreLoaded : {1}",
currentMethod,
asm.FullName);
logger.InfoFormat("###### {0} - ************** Assemly CodeBase : {1}",
currentMethod,
asm.CodeBase);
}
}
}
}
}
Config
<configuration>
<configSections>
<!-- ================================================================================= -->
<!-- LOG4NET -->
<!-- ================================================================================= -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<!-- ================================================================================= -->
<!-- LOG4NET -->
<!-- ================================================================================= -->
<log4net>
<root>
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="[SimpleAppConfig] %date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<!-- ================================================================================= -->
<!-- LogFile location : under App_Data -->
<!-- ================================================================================= -->
<file value="log-file.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
<configSections>
<!-- ================================================================================= -->
<!-- LOG4NET -->
<!-- ================================================================================= -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<!-- ================================================================================= -->
<!-- LOG4NET -->
<!-- ================================================================================= -->
<log4net>
<root>
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="[SimpleAppConfig] %date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<!-- ================================================================================= -->
<!-- LogFile location : under App_Data -->
<!-- ================================================================================= -->
<file value="log-file.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
// LOG4NET
[assembly: log4net.Config.XmlConfigurator()]
[assembly: log4net.Config.XmlConfigurator()]