Log4net doesn't log to Application Insights - log4net

I'm using log4net for my MVC application. The log4net.config file is independent from web.config. I added ApplicationInsights.Log4NetAppender to my UI project and moved the aiAppender from web.config to log4net.config. Somehow the application is able to log data into the Logs.txt, but it doesn't log to ApplicationInsights.
Please help me to figure out this issue.
Here is my log4net.config:
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="App_Data/Logs/Logs.txt" />
<encoding value="utf-8" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
</layout>
</appender>
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="aiAppender" />
</root>
</log4net>
The InstrucmentationKey for applicationinsights is reading from appsettings.
TelemetryConfiguration.Active.InstrumentationKey = WebConfigurationManager.AppSettings["InstrumentationKey"];
In AdaptiveSamplingTelemetryProcessor, I'm using adpative sampling.
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
<ExcludedTypes>Event</ExcludedTypes>
</Add>
I could see all dependencies and requests get logged on ApplicationInsights, but couldn't find any data from log4net.

If the problem is in log4net, you can best enable log4net internal debugging:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
And write it to file:
<configuration>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
...
</configuration>
If there is any exception you will find it in the log file. It could also be that the AI logger uses buffering, or the application insights is buffering and not flushed when your application exits.
more on Log4net Troubleshooting
flush application insights when your ASP.NET Core application exits

This issue drove me nuts for hours.
You need to add an appender to log4net so it can write to application insights:
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message%newline"/>
</layout>
</appender>
Next set the key or connection string in your startup so log4net can use it. The updated code for .NET 5 / 6 is:
services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
ConnectionString = Configuration["ApplicationInsights:ConnectionString"],
EnableActiveTelemetryConfigurationSetup = true
});
Full info here.

Related

Log4net: Multiple configuration files but only one actually used

I am trying to refactor a little bit outdated code and can not find solution for log4net logs: I have multiple project each one of them defined it own log4net logger like this:
(using Common.Logging.Log4net.Universal and Common.Logging.Core and Common.Logging, log4net version 2.0.12.0)
app.config
...
...
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Universal.Log4NetFactoryAdapter, Common.Logging.Log4Net.Universal" />
</logging>
</common>
<appSettings>
<add key="log4net.Config" value="Current.Project.Unique.Name.log4net.config" />
<add key="log4net.Config.Watch" value="True" />
</appSettings>
...
...
and actual Current.Project.Unique.Name.log4net.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="CurrentProjectUniqueAppenderName" type="log4net.Appender.RollingFileAppender">
<file value="LogFolder\Current.Project.Unique.Name.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="CurrentProjectUniqueAppenderName" />
</root>
</log4net>
</configuration>
and in code I am trying to use this logger like this:
private static readonly ILog Logger = LogManager.GetCurrentClassLogger();
private void function1()
{
Logger.Debug("I am logging here");
}
so it look like everything OK and should work but actually what happens that only 'Startup project' actually reading (?) and using xxx.log4net.configuration file (it's own) and no other project is reading or using they <project.name>.log4net.configuration file.
Why is this ? How I can configure log4net so each project will use it own configuration file and only fallback to startup-project configuration in case it own is not defined ?

Log4Net not creating a log file

I am using log4net to log the error in my application.But the log file is not getting created.As far as I can see,the code is fine.
Web.config code
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<!-- Pattern to output the caller's file name and line number -->
<conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="C:\Demo\example.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
In the AssemblyInfo.cs file,I have added the following code
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
In the class where I want to track the errors,I have added the following code
private static readonly ILog logger = LogManager.GetLogger(typeof(ProviderRepository));
I am using the logger as so in the catch block.
logger.Error(Ex.Message);
But I dont see the Log file.Am I doing something wrong here?
You should check if your apppool user has access to C:\Demo\, next you can enable log4net internal debugging which will tell you if there is any problem in your configuration or file access etc:
<configuration>
...
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Log4net FAQ
Thanks a lot for all your suggestions guys.I was able to figure this one out.I had write the below line of code in the Global.asax file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
I was writing it earlier in the Assembly.info.cs file.

log4net does not roll over the log file sometimes when rollingstyle set to date

I have a Windows C# application which uses log4net for logging. This is how the loggers are configured:
<log4net>
<appender name="DebugFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Local\logs\ApplnTrace.log" />
<threshold value="INFO" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%5p] - (%file:%line) %m%n" />
</layout>
</appender>
<appender name="MSGFileAppender" type="log4net.Appender.RollingFileAppender">
<file value=".\local\logs\MsgTrace.log" />
<threshold value="INFO" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d %n%m%n" />
</layout>
</appender>
<logger name="ApplnLogger">
<appender-ref ref="DebugFileAppender" />
</logger>
<logger name="MsgLogger">
<appender-ref ref="MSGFileAppender" />
</logger>
</log4net>
The files are rolled over based on date sometimes and sometimes does not and when files are not rolled over, the logging also stops. Can anybody help me find out why?
log4Net is designed to fail quietly. When things stop working, there's usually a problem (most often, it's a config issue or a filesystem security issue).
You might want to try enabling internal log4net debugging. Park this key in the <appSettings> element of your app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
then start your app. Log4net will spew a bunch of debugging info. It gets written to System.Console and to the System.Diagnostics.Trace system. You can catch the trace messages from an attached debugger or by adding a trace listener in the app.config file. If the trace listener writes to a file, make sure that your process has write access, otherwise you'll see nothing:
<configuration>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt"
/>
</listeners>
</trace>
</system.diagnostics>
...
</configuration>
There are a number of different trace listeners you can wire up here, including ones that write to the windows event system.
More here:
http://haacked.com/archive/2006/09/27/Log4Net_Troubleshooting.aspx
http://logging.apache.org/log4net/release/sdk/log4net.Util.LogLog.InternalDebugging.html
Without source, it's hard to tell. Does the application also stop working? If yes, find the fatal flaw in your application.
If not, judging from the log4net JIRA, there's plenty of issues with the RollingFileAppender(see: log4net JIRA) :
"RollingFileAppender stops logging intermittently when it tries to roll over the log file"
"RollingFileAppender with rollingStyle="Date" and maximumFileSize both are not working Simultaneously."
Maybe it's one of those issues that's hurting you.

log4net, can't get it working with .net 4.0 mvc app

Trying to get log4net setup for .net 4.0 asp.net mvc2 app. I have bare minimum configuration but nothing is getting logged. Am I missing something?
referencing log4net 1.2.10 released version dll
added in sections
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
added section
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<!-- Pattern to output the caller's file name and line number -->
<conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="c:\\example.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
trying to log message with log4net.LogManager.GetLogger("global").Error("test error");
But there is nothing getting logged and no error. Tried lot of config variations like only console, only rollingfile, to file appender only. but nothing works. And yes it's .net 4.0 full project not client profile.
What could be wrong in here?
Did you start log4net?
protected void Application_Start()
{
XmlConfigurator.Configure();
...
}

How can I enable logging for an NServiceBus Generic Host

I didn't want to make the title too long but this question specifically refers to running an NServiceBus Generic Host as a Windows Service (thanks to TopShelf) configured to run as Local System (on a Vista machine)
In a previous question I explain why I decided to adapt the PubSub sample to run as a Windows Service so that I can easily stop and start the service to fully prove to myself that NServiceBus was doing what it was supposed to do.
For some reason I can't get Log4Net to log anything to disk, so this could well just be a Log4Net (newbie) configuration problem?
Below is my brute-force attempt to get some sort of tracing going - all I'm getting so far is files writen as follows:
C:\logs\<-GUID->log4net.log
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, NServiceBus.Core"/>
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<!-- in order to configure remote endpoints use the format: "queue#machine"
input queue must be on the same machine as the process feeding off of it.
error queue can (and often should) be on a different machine.
-->
<MsmqTransportConfig
InputQueue="worker2"
ErrorQueue="error"
NumberOfWorkerThreads="1"
MaxRetries="5"
/>
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="Messages" Endpoint="messagebus" />
</MessageEndpointMappings>
</UnicastBusConfig>
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, NServiceBus.Core">
<arg key="configType" value="INLINE"/>
</factoryAdapter>
</logging>
</common>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="c:\logs\Subscriber2.log" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<datePattern value="yyyyMMdd" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionpattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.appender.eventlogappender">
<applicationname value="Subscriber2.EndPointConfig_v1.0.0.0" />
<layout type="log4net.layout.patternlayout">
<conversionpattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="EventLogAppender" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="TraceAppender" />
</root>
</log4net>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="c:\logs\log4net.log" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
NSB will not pick up log settings from config files as default. To do this implement IConfigureLogging in your endpoint config class.
More info here:
http://tech.groups.yahoo.com/group/nservicebus/message/3655
Hope this helps!
/Andreas
It looks as if your other two appenders are throwing exceptions while trying to log. I suspect the %property{NDC} in your patterns - remove them from the pattern and try again.
If your pattern contains %property{X} then you need to set a property with key "X" using code such as
ABC.Properties["X"] = /* some value */
where ABC is either a LoggingEvent instance or ThreadContext or GlobalContext.
I don't know if you've set properties with key "NDC", but I suspect not...

Resources