Can't get Log4Net to work in my ASP.NET website :( - asp.net

really simple question -> i can't seem to get any data from Log4Net in my ASP.NET application. I've got a simple ASP.NET website, which references a class library. In this class library, I have some lines that call the logger.
I'm trying to read the log4net output data in my Visual Studio 2008 debugging Output window.
Here's my code and my configuration...
//Class Library project
//File: Foo.cs
public class FooService
{
private static readonly ILog log = LogManager.GetLogger(typeof(FooService));
public FooService()
{
// NOTE: To play with my L4N settings, I'll call Debug once, then Info once.
log.Info("Starting Constructor");
// ... snip ...
log.Debug("Leaving Constructor");
}
}
// ASP.NET Website project
// File: global.asax
void Application_Start(object sender, EventArgs eventArgs)
{
log4net.Config.XmlConfigurator.Configure();
}
// File: Whatever.aspx.cs
// A delegate method (when a user clicks a button) creates the FooService() instance.
// File: web.config
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" />
// ....
</configSections>
<log4net>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<backColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
</appender>
<appender name="OutputDebugStringAppender" type="log4net.Appender.OutputDebugStringAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<backColor value="Blue" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="App_Data\logging\log-append.txt"/>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="OutputDebugStringAppender" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="ColoredConsoleAppender" />
</root>
<!-- Specify the level for some specific categories -->
<logger name="DotNetOpenAuth">
<level value="ALL" />
</logger>
</log4net>
Cheers for any help or suggestions...
EDIT: Added the RollingLogFileAppender.

I had this same problem and I think it was looking at the wrong web.config or something. I finally separated out log4net.config from web.config and put a path to it \inetpub\Logs\log4net.config and all is well.
UDPATED ON REQUEST: edited from a slightly more complicated version.
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level (%logger:%line) - %message%newline" />
</layout>
</appender>\
<root>
<!--ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF-->
<level value="ALL" />
<appender-ref ref="TraceAppender" />
</root>
</log4net>
And it is configured in code as follows:
var logpath = WebConfigurationManager.AppSettings["LogConfigPath"] ?? #"\Inetpub\Logs\log4net.config";
var finfo = new System.IO.FileInfo ( logpath );
XmlConfigurator.Configure( finfo );

ASP.Net has restriction on usage of filesystem access, so try to explicitly point directory under App_Data (were it is allowed)
Here my working sample:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="App_Data\logging\log-file.txt"/>
Or with rollover
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="App_Data\logging\log-append.txt"/>

Ok, found the answer. I needed to use a TraceAppender.
The application configuration file
can be used to control what listeners
are actually used. See the MSDN
documentation for the Trace class for
details on configuring the trace
system.
Events are written using the
System.Diagnostics.Trace.Write(string,string)
method. The event's logger name is
passed as the value for the category
name to the Write method.
Here's my config file data...
<log4net>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="TraceAppender" />
</root>
</log4net>

There are atleast 2 possible problems:
The way the address to the file is specified, try using an absolute path instead.
The process making the call needs rights to modify the file. Check that the user account making writing to the log file has rights to do so.
To debug it I would create and empty directory, give everyone full control, configure to log to that directory. Then test it, see that it works, then gradually tighten the security to an acceptable level.

I added the following line Global.asax file, and it works..!!
log4net.Config.XmlConfigurator.Configure();

Related

Log4Net Configuration - No system Log file created

I'm having trouble getting log4net to create the log file when errors are recorded.
I'm using ninject to inject dependancies for my objects related to log4net, as ive created a wrapper:-
public interface ILogManager
{
ILog GetLog(Type typeAssociatedWithRequestLog);
}
public class LogManagerAdapter : ILogManager
{
public ILog GetLog(Type typeAssociatedWithRequestLog)
{
var log = LogManager.GetLogger(typeAssociatedWithRequestLog);
return log;
}
}
In NinjectConfigurator.cs :-
private void ConfigureLog4net(IKernel container)
{
XmlConfigurator.Configure();
var logManager = new LogManagerAdapter();
container.Bind<ILogManager>().ToConstant(logManager);
}
private void AddBindings(IKernel container)
{
ConfigureLog4net(container);
}
In my webconfig i have the following :-
<configSections>
<section name ="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="..\\..\\logs\\WebApi2Book.Api.Log"/>
<appendToFile value="true"/>
<maxSizeRollBackups value="-1"/>
<countDirection value="1"/>
<maximumFileSize value="5MB"/>
<rollingStyle value="Composite"/>
<preserveLogFileNameExtension value="true"/>
<staticLogFileName value="false"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception"/>
</layout>
<logger name="NHibernate">
<level value="ERROR"/>
</logger>
<logger name="NHibernate.SQL">
<level value="ERROR"/>
</logger>
<root>
<level value="ALL"/>
<appender-ref ref="LogFileAppender"/>
</root>
</appender>
</log4net>
In the Global.asax class, Im testing the logger is actually being injected correctly and then testing logging an error in the Application_Start() method.
protected void Application_Start()
{
var log = WebContainerManager.Get<ILogManager>().GetLog(typeof(WebApiApplication));
log.Error("Yey!!!! works!");
log.Debug("Yey!!!! works!! Debug");
}
I cant find any problems when i debug the program, i've checked that IsDebugEnabled is set as TRUE, and the logger in injected correctly as expected.
The only issue is that the log file isn't generated.
Your problem is that in your root logger you are referencing an appender called "LogFileAppender" but in fact your appender is called "RollingFileAppender" - the appender name must be the same on both places:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
…
<root>
<level value="ALL"/>
<appender-ref ref="RollingFileAppender "/>
</root>

Log4net doesn't log online

I'm trying to use log4net to log errors on my MVC 4 website. It works fine offline, but when we publish the website, log4net doesn't even create the log file.
Here is the Web.config code:
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="mylog.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<header value="**"/>
<footer value="**"/>
<conversionPattern value="%newline%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="LogFileAppender"/>
</root>
</log4net>
I added this to the Assembly:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Here is my code to call the logger:
public void logInfo(string message)
{
log4net.Config.XmlConfigurator.Configure();
logger.Info(message);
}
This is bcoz,the root folder doesn't have write permissions where you are trying to create the log file.
steps to provide write permissions:
1) right click on "folder"
2) go to properties
3) click on security
4) Click on add-> add everyone-> check on full control.
it will work fine now.

Does the Log4net SMTPAppender send email Asynchronously?

Does the Log4net SMTPAppender send email asynchronously? If it doesn't, how can I send logging emails asynchronously?
My log4net.config is:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<appender name="SMTPAppender" type="log4net.Appender.SMTPAppender">
<authentication value="Basic" />
<to value="xxx#xx.com" />
<from value="yyy#xx.com" />
<username value="yyy#xx.com" />
<password value="yyy" />
<subject value="xxx" />
<smtpHost value="smtp.xx.com" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN" />
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger %newline %message%newline%newline%newline" />
</layout>
</appender>
<root>
<level value="INFO"></level>
</root>
<logger name="MyLogger">
<level value="INFO"></level>
<appender-ref ref="SMTPAppender"></appender-ref>
</logger>
</log4net>
</configuration>
You could just call the logging method asynchronously like this:
Task.Factory.StartNew(() => log.Info("Message I want to email"));
I actually got this suggestion from the following SO article:
How do I create an asynchronous wrapper for log4net?
There is a simple workaround before the solid solution is released.
public class SmtpAsyncAppender : SmtpAppender
{
protected override void SendEmail(string messageBody)
{
Task.Run(() => base.SendEmail(messageBody));
}
}
It presumes that SmtpAppender.SendEmail is thread-safe and reenterable. It is for log4net v1.2.13.0 and there is no reason not to be in the future.
Log4net has not built in appender that is asynchronous. If you need that functionality you need to write your own appender. Downloading the log4net source code should get you started...

Log4Net: How to specify different level to separate appenders for ASP.NET

For Log4Net used in ASP.NET,
how do I specify specify different levels to separate appenders in web.config?
Thanks.
Pure guesswork at play here.
Looked at the documentation & thought, this could be the way to do it.
Note: DEBUG level messages are logged to console & WARN level messages are logged to eventlog.
I hope it works :)
<log4net>
<!-- A1 is set to be a ConsoleAppender -->
<appender name="A1" type="log4net.Appender.ConsoleAppender">
<!-- A1 uses PatternLayout -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<logger name="DebugLogger">
<level value="DEBUG" />
<appender-ref ref="A1" />
</logger>
<logger name="WarnLogger">
<level value="WARN" />
<appender-ref ref="EventLogAppender" />
</logger>
</log4net>
This works for SmtpAppender at least. Guess it will work for other appenders too, but I haven't tested it
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>

unique log file with log4net

hi i'm using log4net for logging my website.
Every day a new file is created like "filename.log24-06-2009"
this is the code in the web.config file:
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="App_Data\Missioni.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<!--<datePattern value="yyyy-MM-dd" />-->
<maxSizeRollBackups value="5" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Header]
" />
<footer value="[Footer]
" />
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
How can i do for use a unique log file?
thanks
The question' a bit unclear, so please comment if I'm off. If you want to change how the files are created, uncomment the datePattern block and you can specify the file name layout, for example if you wanted the log to change monthly:
<datePattern value="yyyy-MM" />
When the pattern changes (midnight with the standard datePattern) a new file is created, change the pattern to so it only rolls to a new file when you want.

Resources