I have downloaded the log4net.dll and added that as a service reference.
One of the project I have created has app.config where I have made the following configurations
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net"type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="C:\\Users\\<myid>\\Desktop\\error.log"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<system.serviceModel>
<bindings />
<client />
</system.serviceModel>
</configuration>
I have an Entry form and created and declared
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
this inside the partial class and the the logging I have used here
private void Entry_Load(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
logger.Debug("logged");
}
and I have added
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "app.config", Watch = true)]
in Assemblyinfo.cs class
and also added this in the main.cs class
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
logger.Debug("app started");
}
The log file itself is not created and when I debug it runs through these codes properly.
I am using log4net.dll version 1.2.13 for desktop applications using .net 4.0 c#.
How can I achieve this?
You have initialized log4net 3 different ways, first make a choose how to initialize and configure log4net. The only way to configure an application using the System.Configuration APIs is to call the log4net.Config.XmlConfigurator.Configure(). So you have to remove the assembly: log4net attribute. If you want to use a log4net configfile, you can best do this by the attribute in the assembly.cs. The last way enables you to change the configuration while your application is running.
Please read the manual on configuring log4net
#peer is right, you need to pick one method of configuring log4net and use it correctly.
I think your immediate problem though is you've specified app.config as the config file in your assembly attribute, but you must specify your_app_name.exe.config as that will be the file's name after the project is built (the name will differ depending on the actual name of your app, look in the build output directory to see what it is called)
Alternatively, as "If neither of the ConfigFile or ConfigFileExtension properties are specified, the application configuration file (e.g. TestApp.exe.config) will be used as the log4net configuration file." just omit the ConfigFile attribute altogether:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
(The documentation states that is is possible to watch an app.config file, as long as you pass the FileInfo to ConfigureAndWatch or use an assembly attribute.)
If you have any more problems, though, set log4net into debug mode with the declaration <log4net debug=true> in the config and check the Trace output at runtime for any reported configuration issues.
Related
I am developing an AutoCAD 2012 plugin using .net API"s of autocad. The Autocad plugin's are dll which are loaded into the Autocad runtime when the Autocad is started. I have been able to successfully log from log4net using Visual Studio developement environment. However, when I run the plugin outside of Visual Studio, that is when I deploy my plugin, the log4net does not log any messages or even create a log file. Here is the logging related code and the configuration file.
log4net_autocad.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
</configSections>
<log4net>
<appender name="AutocadRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="${NIRVANA_SOFTWARE_INSTALL_PATH}Relay_Manager_Autocad.log"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="0" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p [%C.%M] %m%n"/>
</layout>
</appender>
<logger name="AutocadFile">
<level value="All"/>
<appender-ref ref="AutocadRollingFileAppender"/>
</logger>
</log4net>
</configuration>
myPlugin.cs: Code to congifure logging
public class MyPlugin : IExtensionApplication {
private static log4net.ILog log;
void IExtensionApplication.Initialize() {
...
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("log4net_autocad.config"));
log = log4net.LogManager.GetLogger("AutocadFile");
}
void IExtensionApplication.Initialize() will execute when the Autocad is started. Couple of things that I have checked:
Checked that the Autocad Plugin is properly loaded in Autocad, which
means that log4net initialization code has run.
Checked that log4net config file (log4net_autocad.config) is copied
in the bin directory of the deployed application
The strange thing is that when I load the plugin in developement environment(VS 2010), the plugin logs properly. So why is the log4net not logging (or even creating a log file) in deployment.
EDIT:
I checked some additional stuff
In the plugin just before I log, I checked following through alert dialogs.
The log.Logger.Name properly returns the name of the logger that I am using.
log.Logger.IsEnabledFor(log4net.Core.Level.All) returns false, even though I have configured Level Value=All in the config file.
EDIT-2
I tried to define config file as explained in the referring url of the answer. I am quoting the approach as outlined in the document.
2.] Application Configuration File: [AppName].exe.config, [AppName].dll.config
The application-level configuration, [AppName].exe.config or [AppName].dll.config, is where
most of this document will spend its time. This configuration file will contain all applicationlevel settings and can even be used to define the use of and default values for settings
associated with the Roaming-User and Local-User configuration files. These files are
typically stored in the same directory as the application executable, but can be placed
elsewhere if necessary. There will be much more discussion on this to come.
The above approach suits my application, but I still can't get the logger to log anything at all.I defined a log4net config file with name RelayAnalysis_Autocad.dll.config and supplied it to the log4net for configuration. I think there is something else to it that I am not able to understand. I have started doubting whether we can log using log4net from autocad plugin?
I also removed the environment path and hardcoded it so as to eliminate any issues regarding the reading of environment variable. Still no luck.
On deploy, you should store the plugin configuration in one of the default config files:
User.config
acad.exe.config
machine.config
Probably, the User.config is the best file to carefully change during setup. Moreover you should design and code the changes so that they can be reverted on uninstall.
Doublecheck that you have properly replaced the ${NIRVANA_SOFTWARE_INSTALL_PATH} during setup and that the folder has proper permissions.
Furthermore, I would try to either add to the AssemblyInfo.cs the following line
[assembly: log4net.Config.XmlConfigurator(ConfigFile="AbsolutePathToTheConfig")]
(in which case you shouldn't call XmlConfigurator.Configure) or use an absolute path in the call to
log4net.Config.XmlConfigurator.Configure(new FileInfo("AbsolutePathToTheConfig"));
Finally, note that the log4net documentation about XmlConfigurator.Configure states that the configuration file used can be a XML not matching the .NET config rules.
The configuration file must be valid XML. It must contain at least one element called log4net that holds the log4net configuration data.
Thus, in the log4net_autocad.config file you can skip the <configuration> element:
<log4net>
<appender name="AutocadRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Absolute\Path\To\Relay_Manager_Autocad.log"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="0" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p [%C.%M] %m%n"/>
</layout>
</appender>
<logger name="AutocadFile">
<level value="All"/>
<appender-ref ref="AutocadRollingFileAppender"/>
</logger>
</log4net>
I prefer the external config files for log4net as the log4net can monitor those files and the level can be changed without chaning the app/web.config file. I am struggling a bit to do that in NServiceBus. I am using Here is my external config file
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingFile" type="log4net.Appender.FileAppender">
<file value="C:\Logs\NServiceBusApplication.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
The easiest way to do so is to place an attribute in AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "ApplicationName.log4net.xml", Watch = true)]
This doesn't work in NServiceBus (I am using NServiceBus.Host.exe). Then I tried calling
SetLoggingLibrary.Log4Net(() => XmlConfigurator.Configure(log4netConfigUri));
before Configure.With in EndpointConfig. With this log4net reads the config file from the correct location, it doesn't watch for it, so when I change the log level, it isn't reflected in the app.
Next I tried with appSettings
<appSettings>
<add key="log4net.Config" value="ApplicationName.log4net.xml"/>
<add key="log4net.Config.Watch" value="True"/>
</appSettings>
Again, log4net reads this and subsequently reads the ApplicationName.log4net.xml, it still doesn't watch for it.
How do I configure the log4net in NServiceBus service that is using NServiceBus.Host.exe to
Read the config file form external config file (i.e. log4net config is not within app.config)
Watch the external config file so that any changes to the external config file are reflected.
If you're using the assembly attribute, use:
SetLoggingLibrary.Log4Net(); // no parameters
This should also work:
SetLoggingLibrary.Log4Net(() => XmlConfigurator.ConfigureAndWatch(log4netConfigFileInfo));
Or this:
XmlConfigurator.ConfigureAndWatch(log4netConfigFileInfo)
SetLoggingLibrary.Log4Net();
NServiceBus >= 5.0 has a separate nugetPackage for log4Net: NServiceBus.Log4Net
Instead of calling: SetLoggingLibrary.Log4Net(x => ...);
use the following statements:
log4net.Config.XmlConfigurator.Configure();
LogManager.Use<Log4NetFactory>();
Or refer to this sample on how to programmatically configure the appenders:
https://github.com/Particular/NServiceBus.Log4Net/blob/develop/src/Sample/LoggingConfig.cs
I configured my log4net to watch on changes made to the app.config file.
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
When I run my app and change things in the config file, these changes only take effect when I restart my app. Why could this be?
Is there also a way to tell log4net to watch on changes in the app.config? Like:
<appender name="FileAppender" type="log4net.Appender.FileAppender" >
<watch value="true" />
</appender>
------------- EDIT -------------
I tried now to use a separate config-file: log4net.config.
It looks like this:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="c:\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c (line %L) -- %m%n" />
</layout>
</appender>
<root>
<appender-ref ref="FileAppender" />
</root>
</log4net>
In my assemblyInfo.cs I wrote the following:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
The class that logs to the file looks like this:
ILog myLogger = LogManager.GetLogger(typeof(Form1));
myLogger.Debug("test");
This works like the old version. logfile entries are made, but when I change my log4net.config during runtime, these changes are not applied.... "Watch=true" should enable that feature, right?
HA!, I was just encountering the same problem, running unit tests that require logging.
Adding this line fixed it:
log4net.Config.XmlConfigurator.Configure();
My App.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
I also do have this:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
According to log4net documentation, the Watch feature does not work for application configuration files (app.config, web.config):
Because the System.Configuration API does not support reloading of the config file
the configuration settings cannot be watched using the
log4net.Config.XmlConfigurator.ConfigureAndWatch methods.
So if you need the log4net configuration to be re-configurable, you will need to place it in a separate XML file and your application needs to have sufficient permissions to read the file:
The file to read the configuration from can be specified using any of the log4net.Config.XmlConfigurator methods that accept a System.IO.FileInfo object. Because the file system can be monitored for file change notifications the ConfigureAndWatch methods can be used to monitor the configuration file for modifications and automatically reconfigure log4net.
Even though I'm terribly late to the party - here's, what helped me: a simple call to log4net.LogManager.GetLogger("DUMMY"); at the very beginning of my program. I put it in the very first line of program.cs's Main() method. No need to assign the logger to any object, merely a polite request to log4net to read the assembly's attributes as stated here.
Using attributes can be a clearer method for defining where the application's configuration will be loaded from. However it is worth noting that attributes are purely passive. They are information only. Therefore if you use configuration attributes you must invoke log4net to allow it to read the attributes. A simple call to LogManager.GetLogger will cause the attributes on the calling assembly to be read and processed. Therefore it is imperative to make a logging call as early as possible during the application start-up, and certainly before any external assemblies have been loaded and invoked.
For a Windows service written in C# 4, I have log4net configured and working fine in development. But not in production.
Here is my config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs/Log.xml"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="100MB"/>
<layout type="log4net.Layout.XmlLayout">
<param name="Prefix" value=""/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
Within my AssemblyInfo.cs I have:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
When I run the app locally, stuff is written to the log as expected. When I run it on the server, the log file is created at the correct path but it remains empty. Not a single character is written to the log.
Clearly my configuration is being picked up since the file is at the proper location with the proper extension.
As a workaround, I removed the [assembly: log4net.Config.XmlConfigurator(Watch = true)] line from the assembly and just did it in code on application start.
I just had the same issue and fixed that, [assembly: log4net.Config.XmlConfigurator(Watch = true)] was in ninjectwebcommon file instead of assembly info. After i moved that to assemblyinfo it start working
This is a silly question... but are you sure your service has started correctly and is doing stuff?
I'd add the console appender and maybe the eventlong appender too, and try running your service as a console app, if possible, to have a look?
I'd say, since the log file is being created, things look fine with log4net...?
I have two projects configured identically for log4net. One project logs fine; however, the other does not log at all.
The Logger in the project that is not logging returns IsFatalEnabled = false, IsErrorEnabled = false, IsWarnEnabled = false, IsInforEnabled = false and IsDebugEnabled = false.
I've copied and pasted from one project to the other, replaced the file completely and tried removing all whitespace.
What could be causing the one project not to properly be reading the correct levels from the app.config?
app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="logfile.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date: %-5level – %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>
Program.cs
using log4net;
class Program
{
private static readonly ILog Log = LogManager.GetLogger("SO");
static void Main(string[] args)
{
Log.Info("SO starting");
}
}
It seems that the app.config file was not configured to be watched by log4net.
I added the following line to AssemblyInfo.cs and logging is now enabled:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Weird, since I didn't add this line to the the project that was working.
EDIT:
Looks like the project that was working did have the line after all. I must have forgotten.
// This will cause log4net to look for a configuration file
// called [ThisApp].exe.config in the application base
// directory (i.e. the directory containing [ThisApp].exe)
// The config file will be watched for changes.
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
The solution for me was to use XmlConfigurator.Configure() in the program's startup code. However, my situation differed in that I was using the Autofac.log4net module to register the ILog in an Autofac container. In this instance, using XmlConfiguratorAttribute (with Watch set to either true or false) left the logger unconfigured.