Reputation: 105
I'm able to create logs but unable to write exception string to it...the logs.txt remains empty...
This is the catch block :
catch (Exception ex)
{
Logging.LogError(ex.ToString());
return new DataTable();
}
Logging.cs :
public class Logging
{
public readonly ILog log = LogManager.GetLogger(typeof(Logging));
public static void LogError(string exception)
{
log4net.Config.XmlConfigurator.Configure();
}
}
web config :
<log4net>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs\Log_%date{dd-MM-yyyy_HH-mm-ss}.txt"/>
<appendToFile value="true"/>
<maxSizeRollBackups value="-1"/>
<!--infinite-->
<staticLogFileName value="true"/>
<rollingStyle value="Once"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="file"/>
</root>
</log4net>
Upvotes: 2
Views: 9147
Reputation: 14972
To use log4net you need to:
log4net.Config.XmlConfigurator.Configure();
private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));
log.Info("Exiting application.");
In your example you need to declare the logger in the class where the catch block is, initialize log4net at the start of your app, and use the instance to log the exception
Upvotes: 0
Reputation: 2797
public static class Logging
{
private static ILog _logger = null;
private static log4net.ILog Logger
{
get
{
if(_logger == null)
{
_logger = LogManager.GetLogger(typeof(Logging));
log4net.Config.XmlConfigurator.Configure();
}
return _logger;
}
}
// Better to use Exception object. This gives you more details
public static void LogError(string msg, Exception ex)
{
Logger.Error(msg, ex);
}
Check permissions on your web server and use full path to log file. Also use debug="true" for log4net. Here is example of working log4net configuration, which rolls files on size. You could change it later.
<log4net debug="true">
<root>
<level value="ALL" />
<appender-ref ref="file" />
</root>
<appender name="file" type="log4net.Appender.RollingFileAppender, log4net">
<file value="wwwroot\logs\Log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maximumFileSize value="1MB" />
<maxSizeRollBackups value="5" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%-5level] (%thread) %logger - %message%newline" />
</layout>
</appender>
Upvotes: 2
Reputation: 2171
Change your class to
public class Logging
{
public static readonly ILog log = LogManager.GetLogger(typeof(Logging));
public static Logging()
{
log4net.Config.XmlConfigurator.Configure();
}
public static void LogError(string exception)
{
log.Error(exception);
}
}
Upvotes: 0