log4net not logging from Autocad Plugin on deployment - log4net

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>

Related

Log4net RollingFileAppender not writing when application runs as a service

I have an C# application that can run on Windows 10 either as a console app or as a service, depending on a configuration parameter. I am writing log messages using a log4net RollingFileAppender. I'm using log4net version 4.5. When the application runs as a console app, the rolling file gets written as expected. When it is run as a service the file does not get written. What can I do to get my log file?
Here's the configuration file:
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="TimedFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:/misc/HotspotControlService.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd.lo\g" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="TimedFileAppender" />
</root>
</log4net>
As usual, my own idiocy is the problem. I specified the configuration file in my program by the bare file name, with no folder given. The file exists in the same folder as my executable file. But when running as a service, the working folder is not the folder in which the executable folder lives. I used an absolute path for the configuration file name, and it worked.

SQL Jobs or Task Scheduler call log4net, does not write log file

I write a console application with log4net, my log4net config below
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="Process_Log\" />
<appendToFile value="true" />
<datePattern value="yyyy-MM-dd.TXT" />
<maxSizeRollBackups value="10" />
<rollingStyle value="Date" />
<maximumFileSize value="10MB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %message [%logger] %n" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Run the console application, It has output log files.
But use SQL Server Agent Jobs or Windows Task Scheduler call it,
It didn't write log file.
I figured out the problem. When you run the solution from Visual Studio, log4net finds out the configuration file from the "bin" folder. So, it gets required information to run. But when you run the application by Windows Task Scheduler, the situation is different. This time, the Windows Task Scheduler tries to find out the Configuration file from this location "C:\Windows\System32". Because, when you run Windows Task Scheduler, it treats the default application folder location "C:\Windows\System32".
You can write following codes to navigate the application to load the log4net configuration file. Here, the config file name is "LogConfiguration.config".
var log4NetConfigDirectory =
AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
var log4NetConfigFilePath = Path.Combine(log4NetConfigDirectory, "LogConfiguration.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(log4NetConfigFilePath));
The accepted answer by user3626918 is correct about the problem (wrong working directory). As an alternative to the proposed code change solution you can instead:
Configure the "Start in" directory of your scheduled task (Properties->Actions->Edit...)
Confirm that the account running the scheduled task has permissions to write to the log file destination.

Create multiple logfiles during application run using log4net

I'm using log4net in a c# windows service, so the main application runs every time. I configured log4net to log into a date specific directory. Inside this directory log4net creates a logfile with a timestamp in the filename. This works fine. The probem is, that it only creates a new logfile, when the windows service restarts. This causes the logfile to get very big, expecially if the service runs over several days.
The question is:
Is there a possibility to force log4net to start with a new logfile throughout my code.
This is my log4net config:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file type="log4net.Util.PatternString" value="${ProgramData}\Sirona\Log\AcqSrv\%date{yyMMdd}\AcqSrvAll-%date{HHmmss}.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%2thread] [%-5level] [%logger] - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root> <!-- Do not want NHibernate log -->
</log4net>
Best regards
Emu
I think your problem is solved by the RollingFileAppender: http://logging.apache.org/log4net/release/config-examples.html
http://logging.apache.org/log4net/release/sdk/log4net.Appender.RollingFileAppender.html
It works exactly as a FileAppender but once it reach a maximum size (configurable) it creates another log file.
You can also instruct it to keep only the latest X log files.
Hope it helps.

NServiceBus and Log4Net external config file

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

log4net doesn't watch my app.config

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.

Resources