log4net config settings - log4net

I am into the development of a core dll where I have a class library.I want to use log4net to enable logging for exceptions. I have an app.config file in the class library where i have given the settings for the log4net.However when I test the class library the log4net does'nt create logs until i add the app.config in the calling project inspite of the fact that i had added [assembly: log4net.Config.XmlConfigurator(Watch = true)] in the class libary's assemblyinfo.cs and I am using log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ErrorHandler)) where ErrorHandler is the name of my class library's class where log4net's calling functions are handled.Any ideas on what is going wrong?
Secondly, what I want to acheive is the users of my dll will just pass the location where they want to create logs and whether they want to create logs in event viewer or log files from their app.config? They will not handle any other setting of log4net.
Any suggestions or code snippets for the first issue and the second problem?

Only the "main" app.config is active for a .Net application. Your library config file is simply ignored. Either you transfer your settings to the main config file or you use an external config file for log4net. You configure it then for instance like this (assuming you call it log4net.config):
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Please note that the structure of the config file is a bit different:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="YourAppender" type="..." >
....
</appender>
<root>
<level value="ALL" />
<appender-ref ref="YourAppender" />
</root>
</log4net>
As for your second problem: I am not sure how flexible this has to be. Is it just switching from file appender to event log appender? Depending on your answer you may consider two prepare to configuration files (e.g. file.log4net and eventlog.log4net) and read the configuration as needed (in that case you cannot use the attribute: you call the Configure() method directly) or if your requirements are more complex you might even end up configuring log4net programatically.

Related

log4net items not shown in AppServiceAppLogs

We are using log4net for our application logging in azure.
We configured it according to this document , the logs are stored in
d:/home/LogFiles/Application/Log4netfile-[%processid].txt
we can download the files from https://xxxx.scm.azurewebsites.net/api/dump and I can also see them in Log stream, there it looks like this
2022-02-06T18:22:57 PID[29616] Verbose log4net: Adding appender named [FileAppender] to logger [root].
2022-02-06T18:22:57 PID[29616] Verbose log4net: Hierarchy Threshold []
2022-02-06T18:22:58 PID[29616] Verbose LOG4NET Fatal LOG4NET LOG4NET
2022-02-06T18:22:58 PID[29616] Verbose LOG4NET Debug Message Message
Line items like:
log4net: Adding appender named
are created by log4net during internal setup (using debug=true), and those show up in our AppServiceAppLogs, however, items which are genereted by the logger using:
Logger.Fatal("LOG4NET Fatal LOG4NET LOG4NET");
are visible in stream and files but they are not showing up in AppServiceLogs.
I tried multiple different appenders the only one which shows up in Log-Streams and in files is FileAppender (or RollingFileAppender), all others are not showing in LogStreams or (as expected) in the files.
Based on this https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs#send-logs-to-azure-monitor I assume that everything writen to the files should be than sent to azure-monitor - but in our case this is not hapening. Could you provide some reference about implementation / code how the sending of the files is done, and which process does that ?
I am wandering is there anything which we could configure differently to get the log-items to end up in AppServiceLogs? Or should we use some other appender?
I am aware of the issue in AspNetTraceAppender and I am trying to avoid implementation of new appender.
There are a few things you can look into:
Call log4net configure before writing to your log file (only once is enough):
log4net.Config.XmlConfigurator();
or
log4net.Config.XmlConfigurator.Configure();
and then you can add flushing to your configuration:
<appender name="AzureTraceAppender" type="log4net.Appender.TraceAppender">
<param name="ImmediateFlush" value="true" />
<layout type="log4net.Layout.PatternLayout">
<!-- can be any pattern you like -->
<conversionPattern value="%logger - %message" />
</layout>
</appender>
Immediately, this will flush the message.
In Global.asax, To make log4net read your configuration.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
// Initialize log4net.
log4net.Config.XmlConfigurator.Configure();
}
Make sure Azure Diagnostics has configured to all information needed for debugging.
After that, you can enable internal log4net debugging. Refer internal debugging on this log4net faq page. Standard it should log to your listener you have configured. To the trace element Add the autoflush="true" option . Or find directory on the worker role you can write to and access to read your logs.

Logging With NLog In Azure WebJobs

I've got an NLog configuration which works just fine for my web app (ASP.NET Core).
Now I'm trying to add NLog to my webjobs, but I can't figure out how to do it.
In Program.cs within the webjob project, I need to somehow inject IHostingEnvironment and ILoggerFactory (Both of which I inject into the StartUp constructor of the web app).
Once I know how to do that, I should be able to finish off the configuration.
If that's not possible, what alternatives do I have?
I'm not keen to use the TextWriter class passed into the webjob methods, as I imagine it would be difficult to extract the logs and route them to where I ultimately want it to go.
Following are steps of using NLog in WebJob.
Step 1, install NLog.Config package for your WebJob.
Install-Package NLog.Config
Step 2, add rules and targets to NLog.config files. Following is the sample of writing logs to a file.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
Step 3, get logger instance using LogManager class.
private static Logger logger = LogManager.GetLogger("MyLog");
Step 4, after got the logger instance, you could write log using following code.
logger.Trace("Sample trace message");
logger.Debug("Sample debug message");

Azure AppInsight with Log4Net

I have been trying to write Logs(Trace, Information & Exception) in Azure AppInsights using Log4Net instead of default api Telemetry client. When I run the application from VS2013 neither I get any error message nor am seeing logs in Azure portal.
Pleaes help me figure out this issue.
Note: Am using Log4net appender for AppIinsights.
Web.Config
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="aiAppender" />
</root>
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message%newline" />
</layout>
</appender>
MVC Controller
public class HomeController : Controller
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public ActionResult Index()
{
//Trace.TraceInformation("Home accessed at : {0}", DateTime.UtcNow);
Log.Info(string.Format("Home accessed at : {0}", DateTime.UtcNow));
return View();
}
}
Regards,
Rajaram.
If you are not seeing any log4net output, i'm presuming you are missing some log4net startup code, like this:
log4net.Config.XmlConfigurator.Configure();
which you might want in your startup class / code somewhere. Without that, log4net doesn't know wo read the configuration that's in web.config.
In addition to the answer from #JohnGardner, you can instead add a line to your AssemblyInfo.cs file as so: -
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
There is more discussion on the two approaches in the following question: -
Configure Log4Net in web application
And in a comment in somewhere in that discussion is a link to the log4net FAQs that touches on the differences in the question "When should I log my first message?": -
https://logging.apache.org/log4net/release/faq.html#first-log
I found both of these to be of further use to me.

I have log4net setup just like in the examples, but it still doesn't work

I have log4net setup just like in the examples. In my config file, I have:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
The appender configuration is setup just like it is shown on the log4net site for MS SQL Server surrounded by <log4net>. http://logging.apache.org/log4net/release/config-examples.html
In the AssemblyInfo.cs I have:
[assembly: log4net.Config.XmlConfigurator]
Yet, nothing is showing up in my [dbo].[Log] table.
I have tried using the trace debugging text file, but no errors show up there.
The reason why no errors were showing up in the trace file is because no errors in log4net were happening.
The reason why there was nothing showing up in the [dbo].[Log] table was because the default config on the l4n site has <bufferSize value="100" />. It is my understanding that this bufferSize would mean that l4n would wait until there are 100 messages queued up before writing them to the database. So, to fix it for me, I just changed the value to "1".

JBoss 6.0 M3 and Log4j logging

I'm trying to have application specific logging plus the usual server logs seperately. I have specified 2 in the jboss-logging.xml, one for my app and the other one is usual "server.log" file.
Issue is, both of the log files are getting created and logged at the same time. Can any one help me, what is the change i need to make to log ONLY application specific logs in my logfile?
I fixed this issue. I was defining my application's handler on the section in jboss-logging.xml.Plus i was defining a logger category for my app. The fix was, i removed my application's handler reference from <root-handler> section and hold just the logger category for my app as below:
<logger category="com.X.Y.logger">
<level name="DEBUG"/>
<handlers>
<handler-ref name="myApp"/>
</handlers>
</logger>

Resources