why log4net config file is not being read - c#

I have a file log4net.xml in the root of my solution. The file property for copying to bin is set to Always copy. I have confirmed that the file copies to the bin directory.
Within the config I have set up a file appender (basically a copy paste from the documentation):
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs\\log.log" />
<appendToFile value="true" />
<rollingStyle value="Date"/>
<datePattern value="yyyyMMdd-HHmmss" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
I also have this line in AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]
And loggers are set up like this in code files:
private static ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
I added log4net.Config.XmlConfigurator.Configure(); (and also with FileInfo parameter) to the main Program.cs too.
However if I execute the program the expected log file is not created. I suspect log4net isn't even reading the config file.
Am I missing something? Executing from within VS also doesn't work (though somehow it is picking up the Console Appender part).
Similar posts:
StackOverflow question 1 -- not applicable
StackOverflow question 2 -- not applicable
StackOverflow question 3 -- conforms already
Thanks in advance.
EDIT
So I got this working in VS by deleting a copy/pasted part from the documentation:
<root>
<level value="DEBUG" />
<appender-ref ref="A1" />
</root>
However, running from the exe still doesn't work

Easiest way is to debug log4net error is to dump them to a file under C:\tmp\log4net.txt. This won't answer your original question, but it will give you a clue where to look for.
How do I enable log4net internal debugging?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
<configuration>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
...
</configuration>

I think the issue might be with the double \\ in your path in the config file. Given that when you run the program in Visual Studio and the Console Appender part works, that would seem to indicate that the config file is being read, it just can't write to the file because the path isn't valid. I'm not that familiar with Log4Net, so I don't know if an invalid path would throw an exception or not - it might be getting swallowed.
Try changing the file value in your config to one backslash, like this:
<file value="Logs\log.log" />

I worked this out, I don't know if it's the proper fix - and I have no idea why it worked once in VS - but I think it's just that the config file is not configured properly.
Firstly, since there is a declaration of the file in AssemblyInfo.cs there is no need for log4net.Config.XmlConfigurator.Configure();.
Secondly, I simply had to add both appenders to the root tag:
<root>
<level value="DEBUG" />
<appender-ref ref="A1" />
<appender-ref ref="RollingFile" />
</root>
And that's it. VS outputs on console as well as file, and exe outputs to file.

For the Console application. we can use to configure using the following code
// Path of your log4net config file
string configFilePath = #"/log4net.config";
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead(configFilePath));
var repo = LogManager.CreateRepository(
Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

Related

Log4Net not working in MVC web application but working in console and window application

I have created a solution which consist of class library, MVC web application and console application.
For my class library project is actually responsible to perform logging using log4net which is also included the log4net configuration in the log4net.config. Currently i am facing a problem which the logging is not working when my web application call the logging function from class library. But it's working fine when my console application. My log4net.config looks as below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\\Temp\" />
<datePattern value="'Test.log_'yyyy-MM-dd'.log'" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<appendToFile value="true" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout, log4net">
<conversionPattern value="%date [%thread] %-5level %logger [%method] - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
I have also included the line below in my class library [AssemblyInfo.cs]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
My sample class library function as below:
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Write ()
{
log.Info("Success");
}
I have set the log4net.config Copy to Output Directory to Copy always.
Sample log4net output from console application [Test.log_yyyy-MM-dd.log]:
2019-10-01 12:07:48,923 [1] INFO ClassLibrary2.Class1 [Write] - Success
But there is log file generated for MVC web application. Is there any additional step need to configure for the web application?
I would be grateful for any help with it.
Thanks.
Did you add something in your Application_Start method? (global.asax) like:
string l4net = Server.MapPath("~/log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));
Try To Add ConfigSections in your web.config. Also there's the guide especially for MVC applications.
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
Complete Guide

Setting up Log4Net to log output from a Class Library

I'm trying to setup Log4Net (this is my first time using Log4Net) to log to a text file in an assembly. I'm not getting any errors, but it's also not working. I can breakpoint the lines where I am logging my output and see that they are reached, but like I say nothing happens.
Where am I going wrong?
I have added the following to my packages.config file, inside the <packages> attribute:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="c:\CTI\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
I have added the following line to AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
I added the Log4Net assembly using NuGet and I am logging like this:
private log4net.ILog _Log;
_Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
_Log.Debug("FooBar");
Like I say, no errors but nothing happens either.
What am I missing?
One thing that is wrong is that you are adding the log4net configuration section to the nuget config file (packages.config).
You can have the configuration in the app/web config or in a separate file to which you point from the appSettings, e.g.
configuration is in a file called config.log4net (the copy to output directory attribute of the file is set to copy always) and you add the following entry in app/web.config:
<add key="log4net.config" value="config.log4net"/>
If you don't want to depend on a web/app configuration, you can set the ConfigFileExtension property of the XmlConfiguratorAttribute attribute in AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "log4net", Watch = true)]
Then name the log4net configuration file the same as your exe/assembly plus the configured extension, e.g. MyApplication.exe.log4net or MyLibrary.dll.log4net
Another thing that is wrong is your appender filter. The range that you have set excludes DEBUG level, which you expect to log. Here are all logging levels:
ALL
DEBUG
INFO
WARN
ERROR
FATAL
OFF
As you can see, DEBUG is not between INFO and FATAL.

Log4net Configuration Issue

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

How to include log4net for a class library?

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.

Where will log4net create this log file?

When I set the file value to logs\log-file.txt, where exactly will it create this folder? In the /bin directory?
My web.config looks like this:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="logs\log-file.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
Is this the correct way to log:
ILog logger = LogManager.GetLogger(typeof(CCController));
logger.Error("Some Page", ex); // where ex is the exception instance
If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way
<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />
and then in the code before calling log4net configure, set the new path like below
log4net.GlobalContext.Properties["LogFileName"] = #"E:\\file1"; //log file path
log4net.Config.XmlConfigurator.Configure();
How simple is it? :)
it will create the file in the root directory of your project/solution.
You can specify a location of choice in the web.config of your app as follows:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:/ServiceLogs/Olympus.Core.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value=".yyyyMMdd.log" />
<maximumFileSize value="5MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
<maxSizeRollBackups value="-1" />
<countDirection value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
</layout>
</appender>
the file tag specifies the location.
The file value can either be an absolute path like "c:\logs\log.txt" or a relative path which I believe is relative to the bin directory.
As far as implementing it, I usually place the following at the top of any class I plan to log in:
private static readonly ILog Log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
Finally, you can use it like so:
Log.Debug("This is a DEBUG level message.");
Log4net is saving into your project folder. Something like: \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt.
Where:
SolutionFolder is where you save your solution
ProjectFolder is the folder where your project lives into the solution and
SolutionConfiguration is the folder that contais all the binaries of your project (the default is Debug or Release)
Hope this helps!
FileAppender appender = repository.GetAppenders().OfType<FileAppender>().FirstOrDefault();
if (appender != null)
logger.DebugFormat("log file located at : {0}", appender.File);
else
logger.Error("Could not locate fileAppender");
For the log folder and file stuff, go with #Bens answer.
I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:
ILog logger = LogManager.GetLogger(typeof(CCController));
because it is short and concise.
That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.
I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here
log4net.GlobalContext.Properties["LogFileName"] = #"E:\\file1"; //log file path
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.
I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.
if you want to choose dynamically the path to the log file use the method written in this link: method to dynamic choose the log file path.
if you want you can set the path to where your app EXE file exists like this -
var logFileLocation = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetEntryAssembly().Location);
and then send this 'logFileLocation' to the method written in the link above like this:
Initialize(logFileLocation);
and you are ready to go! :)
In your case, the log file will be in bin\Debug\netcoreapp3.1\ folder
and this may depends on your framework too.
I used Asp.Net core 3.1 so the folder path is bin\Debug\netcoreapp3.1\

Categories