Am used the log4net to log the exception. when the logging is performed but the logs are entered two times in logfiles (LoggerFile.log)
web.config
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="E:\\Logger\\LoggerFile.log"/>
<staticLogFileName value="true" />
<param name="AppendToFile" value="true"/>
<maximumFileSize value="3MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern
value="%date [%thread] %-5level %message%newline%exception %newline" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender"/>
</root>
<logger name="AnonymousLog">
<level value="All" />
<appender-ref ref="FileAppender" />
</logger>
</log4net>
Login.aspx.cs:
I will call to this two methods from Login page to Loggers.cs in Loggers Project
Logger.Initialize();
Logger.Log(LoggingLevel.Error,"Checking Log entered");
Loggers.cs:
Initialize Method:
public static void Initialize(string configFile)
{
if (!isInitialized)
{
if (!String.IsNullOrEmpty(configFile))
XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
else
XmlConfigurator.Configure();
isInitialized = true;
}
else
throw new LoggingInitializationException("Logging has already been initialized.");
}
Log Method:
public static void Log(LoggingLevel loggingLevel, string message)
{
Log(loggingLevel, message, null, null);
}
Another Log method.
public static void Log(LoggingLevel loggingLevel, string message, object loggingProperties, Exception exception)
{
foreach (ILog log in GetLeafLoggers())
LogBase(log, loggingLevel, message, loggingProperties, exception);
}
GetLeafLoggers()
private static IEnumerable<ILog> GetLeafLoggers()
{
ILog[] allLogs = LogManager.GetCurrentLoggers();
IList<ILog> leafLogs = new List<ILog>();
for (int i = 0; i < allLogs.Length; i++)
{
bool isParent = false;
for (int j = 0; j < allLogs.Length; j++)
{
if (i != j && allLogs[j].Logger.Name.StartsWith(string.Format("{0}.", allLogs[i].Logger.Name)))
{
isParent = true;
break;
}
}
if (!isParent)
leafLogs.Add(allLogs[i]);
}
return leafLogs;
}
LogBase Method:
private static void LogBase(ILog log, LoggingLevel loggingLevel, string message, object loggingProperties, Exception exception)
{
if (ShouldLog(log, loggingLevel))
{
switch (loggingLevel)
{
case LoggingLevel.Debug: log.Debug(message, exception); break;
case LoggingLevel.Info: log.Info(message, exception); break;
case LoggingLevel.Warning: log.Warn(message, exception); break;
case LoggingLevel.Error: log.Error(message, exception); break;
case LoggingLevel.Fatal: log.Fatal(message, exception); break;
}
}
}
LoggerFile.log:
The Logs are entered two times in the log files
2015-01-05 07:48:16,023 [21] ERROR Checking Log entered
2015-01-05 07:48:16,023 [21] ERROR Checking Log entered