I'm trying to get Glimpse.Log4Net working in an existing ASP.Net MVC v4 project (in VS2010), following the docs here and here, but although the solution compiles and runs Glimpse and log4net seem to be working correctly, I can't see the log4net stuff in the Glimpse window that I'm expecting and as shown near the end of the page in the 2nd link.
I've got dependancy injection going with Autofac using this method, and I don't think it is interfering because I get entries as expected in the log file.
Can anyone point me in the right direction?
In my controller:
public class QuoteController : Controller
{
private readonly PrintCostEntities db;
private readonly ILog logger;
public QuoteController(PrintCostEntities db, ILog logger)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
this.db = db;
this.logger = logger;
}
public ActionResult Index()
{
this.logger.DebugFormat("Index");
return this.View(this.db.Quotes);
}
}
In global.asax:
public class MvcApplication : System.Web.HttpApplication
{
private readonly ILog logger;
protected MvcApplication()
{
XmlConfigurator.Configure();
this.logger = LogManager.GetLogger(typeof(MvcApplication));
}
protected void Application_Start()
{
this.logger.Debug("Application_Start");
}
}
In web.config:
<configuration>
<configSections>
<section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<system.web>
<httpModules>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" />
</httpModules>
<httpHandlers>
<add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" />
</httpHandlers>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" />
</modules>
<handlers>
<add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
</handlers>
</system.webServer>
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd" />
<log4net>
<appender name="GlimpseAppender" type="Glimpse.Log4Net.Appender.GlimpseAppender">
<threshold value="ALL" />
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<threshold value="ALL" />
<file value="log4net.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="5" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<root>
<appender-ref ref="GlimpseAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
The package has updated to version 1.0 in May 2013 and this version works fine for me in my asp.net mvc4 application.
The log4net tab stays black/inactive (like you mention in your question) when there are no message appended to a GlimpseAppender. There several possible reasons for this:
there is no GlimpseAppender configured - this happened to me, because I had a custom log4net configuration
There is a redirect being done somewhere in you controller(s), after your message was logged. Your typical RedirectResult will redirect via the client resulting in a new request. The GlimpseAppender only logs message for the current http request, so you will not see any messages from before the redirect. (note: so if you do post-redirect-get, most interesting log message are not in teh glimpse log tab)
And then, of course, there are the "usual" log4net reasons why a message is not logged. But I consider that off-topic for this question.
The log4net Glimpse plugin was created by Jess Chadwick and is not yet up to date with the newest version of Glimpse.
You'll want to be using 1.1 version of Glimpse with MVC4, but the log4net plugin has not been updated yet.
The good news is that Glimpse.Log4Net is open source, so you should be able to easily update it to work with the new interfaces. I might even give it a go at updating it myself next week.
In case anyone is looking for more info on this issue - what worked for me:
VS 2013, MVC4, Glimpse 1.8.5, log4net 1.2.11.0
using a separate log4net.config file
in AssemblyInfo.cs I had [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] and in Global.asax Application_Start() I had log4net.Config.XmlConfigurator.Configure();
no log4net output in Glimpse - the tab was visible but it was blacked out
thanks to a tip I found here: https://stackoverflow.com/a/4558906/3590792 I changed the Application_Start() code to:
string l4net = Server.MapPath("~/log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));
and Glimpse log4net started working
Related
I've been trying to pull the debug logs and for whatever reason, I can't seem to get log4net working in my web app:
My Web.config looks like:
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<section name ="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" requirePermission="false" />
</configSections>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value ="%message" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender" >
<file value ="C:\logs\testlog.txt" />
<lockingModel type ="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value ="%message" />
</layout>
</appender>
<root>
<level value ="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
in my Service.asmx.cs:
public class Service : System.Web.Services.WebService
{
public static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Service));
protected void Page_Load(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
My AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Control.ascx.cs:
protected void Page_Load(object sender, EventArgs e)
{
//NOTE: This method will be invoked whenever ANY widget on the dashboard does a postback
log4net.Config.XmlConfigurator.Configure();
}
I have given everyone permissions to the log folder.
The other item I wanted to note is that I can get this exact code to work with a standard console app without any issues. However, when I try to use it on my web app, I do not have any luck. I also wanted to say that this is a web app widget that is part of a bigger application.
One of your problems can be that you have the following in the page load:
protected void Page_Load(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
Remove this because you already have a assembly attribute that does this. The loggers you are using are static variables on the classes. They should be initialized after you call configure. In this case you call it before configure (which is in Page_Load).
I have a test-assembly (MyTestProject) where I want to write some logging using log4net. Thus I created a config-file with the same name as the assembly where I set up the logging as suggested here:
<?xml version="1.0" encoding="utf-8" ?>
<!-- .NET application configuration file
This file must have the exact same name as your application with
.config appended to it. For example if your application is testApp.exe
then the config file must be testApp.exe.config it must also be in the
same directory as the application. -->
<configuration>
<configSections>
<!-- Register the section handler for the log4net section -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<sectionGroup name="NUnit">
<!-- For .NET 2.0 Beta 2 replace the lines with the following -->
<section name="TestCaseBuilder" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.50215.44, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.50215.44, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
</configSections>
<NUnit>
<TestCaseBuilder>
<add key="OldStyleTestCases" value="false" />
</TestCaseBuilder>
<TestRunner>
<!-- Valid values are STA,MTA. Others ignored. -->
<add key="ApartmentState" value="STA" />
<!-- See ThreadPriority enum for other valid values -->
<add key="ThreadPriority" value="Normal" />
</TestRunner>
</NUnit>
<appSettings>
<add key="ApartmentState" value="STA" />
<add key="apartment" value="STA" />
</appSettings>
<!-- This section contains the log4net configuration settings -->
<log4net debug="true">
<!-- Define some output appenders -->
<appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net" >
<param name="File" value="D:/data.log" />
<param name="AppendToFile" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default priority -->
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
Within my code I set up the logging as follows:
[TestFixture]
public class MyTest
{
private readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[TestFixtureSetUp]
public void Init()
{
log.Info("Something to log");
...
}
}
However when I run my tests no such file D:/data.log is created. Even more suspicious when I debug the code and add a watch to the appenders from log I get an empty collection.
I post this together as it stuck me for hours.
I looked into the directory where the file should stay, there was one (apperently from an earlier test-run as its timestamp was not recent). Trying to delete the file got me a message that it is currently in use from nunit-agent-x86.exe. So I killed the process in TaskManager and re-run my tests. Now everything works correct and I get my logging into the file.
This Could have been solved if you give value for key, AppendToFile as true..
As logger appends logging to the existing file and wont try to delete it.
Had something weird start happening to me today. I have an asp.net mvc app with log4net setup and everything had been working fine. Something must have changed somewhere and now nothing is getting logged (no log file is being created).
Here's my global.asax.cx
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
}
Here's my configuration in my web.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\logs\api\ApiLog.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
For some reason the c:\logs\api\apilog.txt file never gets created. However, if I change my application_start method to this it works fine:
log4net.Config.XmlConfigurator.Configure(new FileInfo("DirectPathToMy\web.config"));
Any ideas why calling Configure() is not finding the configuration in my web.config by default?
Don't know why your approach don't work but the issue is that you need to make sure it is activated in your project.
I usually put this as an assembly level reference in my AssemblyInfo.cs under /Properties:
[assembly: log4net.Config.XmlConfigurator()]
Reference:
http://logging.apache.org/log4net/release/manual/configuration.html
I'm trying to configure my C# project to use log4net for RavenDB. I already have log4net working with a FileAppender, but the RavenAppender doesn't seem to be working right now. The following are the steps I have taken so far:
Step 1: Installing log4net.Raven
I installed the log4net.Raven library using the following NuGet Package Manager console instructions (taken from the package website linked to above):
Install-Package log4net.Raven
That command added the log4net.Raven library to my project references.
Step 2: Configuring Web.config
In my Web.config file, I have the following settings, most of which are copy and pasted from the README file for the log4net.Raven project on GitHub (the owner of log4net.Raven also has similar configuration settings published on his blog):
<!-- Example connection string config from blog -->
<configsections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net">
</configsections>
<connectionstrings>
<add connectionstring="Url=http://raven; DefaultDatabase=Log" name="RavenLogs">
<add connectionstring="Url=http://localhost:8080;user=asa;password=asa" name="SecureRaven">
</add>
</add>
</connectionstrings>
<!-- My current config -->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<connectionStrings>
<add name="RavenDB" connectionString="Url=http://localhost:8080;Database=MyDatabase" />
</connectionStrings>
<!-- Example log4net config from README.
My project uses these settings except for the connectionString value,
which is set to "RavenDB" to match the setting name above.
-->
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<!-- LogFileAppender settings here -->
</appender>
<appender name="RavenAppender" type="log4net.Raven.RavenAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<connectionString value="RavenDB"/>
<maxNumberOfRequestsPerSession value="100"/>
<bufferSize value="50" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR" />
</evaluator>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="LogFileAppender" />
<appender-ref ref="RavenAppender" />
</root>
</log4net>
Step 3: Logging from C# code
In my C# code, I have the following:
public class FooController : Controller
{
private static ILog _log = LogManager.GetLogger(typeof(FooController));
public ActionResult Index()
{
_log.Info("Hello World!");
return View("Index");
}
}
That code will write out to a log file on my workstation, so from that I know that log4net in general is working correctly. But for RavenDB, I've been checking the Documents and Logs for MyDatabase through the Raven studio in a web browser, and I do not see any Info level log with the message "Hello World".
Does anyone have any ideas of what the problem could be and how to fix it?
May be the problem is here:
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
if you don't have class named FileAppender in your project you need to add the library name where FileAppender is, for example:
<appender name="LogFileAppender"
type="log4net.Appender.FileAppender, log4net.Raven">
(the syntax for type is =" Fully qualified class name , assembly file name , version , culture , public key token ")
Try debug log4net as here Log4Net Troubleshooting
If you find this line:
log4net: Adding appender named [RavenAppender] to logger [root].
RavenAppender is working
I want to implement logging function into a class library, which is itself referenced in a webservice. I tried to add app.config and did everything needed, but it seems that when an exception is thrown, log4net simply does nothing.
my app.config
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="D:\\mylogfile.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.StringMatchFilter">
<stringToMatch value="test" />
</filter>
<filter type="log4net.Filter.StringMatchFilter">
<stringToMatch value="error" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
in AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "app.config")]
in LogManager.cs:
private static readonly ILog Log = log4net.LogManager.GetLogger
(MethodBase.GetCurrentMethod().DeclaringType);
public static void WriteLog(Exception ex)
{
Log.Error(ex);
}
Can you please tell me what's wrong? How can I get log4net working for my class library?
Thank you
At runtime, config file is always used from host application, unless declared explicitly. Here in case, web.config is being used not app.cofig. Rather mention some other custom config file name and ensure that file is copied in virtual directory of web service. Also as chibacity said, ensure permission on log file. Better keep it in app_data folder for web service host.
You could use some kind of injection, either you build a simple one like:
public interface ILogger
{
void LogInfo(string message);
.
.
.
}
And then you just inject something that matches that interface, like a wrapper for log4net or such.
But, I think the most correct thing is to not log in the class library. Why I think so is because the library itself is not the application, your web service is so your web service should decide what to log. If you want to log exceptions just don't catch them in the class library and let your web service handle the logging. This will also make it easier to centralize the logging.
Please see my answer to the following question:
Use log4net in SDK
It has a log configuration routine that will construct a complete path to a log4net config file. As you are in a webservice it my not be looking where you expect for "app.config".
Also make sure that you have permission to write to "D:\mylogfile.txt" from your webservice.