Create multiple logfiles during application run using log4net - 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.

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.

Log4net file rollingFile not deleting old files

I have log4Net set up with the following config settings in a web service web.config file:
<log4net>
<!-- RollingFile is set to be a File Appender -->
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="c:\temp\Sync.log" />
<appendToFile value="true" />
<maximumFileSize value="50MB" />
<maxSizeRollBackups value="10" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %-50logger - %message%newline%newline" />
</layout>
</appender>
<!-- Set root logger level to DEBUG to have all log -->
<root>
<level value="INFO" />
<appender-ref ref="RollingFile" />
</root>
The issue I am having is when I look in temp I see 17 files
Sync.Log
Sync.log20180424.log
(other sync files with dates)
...
the last one being
Sync.log20180405
I am confused as to why it is not removing the ones beyond 10 days as stated by the maxSizeRollBackups.
I know that by default the is rollingStyle = composite.
With my current config, how would it behave if I let it go?
And as a second - what am I missing in my current settings.
Thanks. I know there are similar questions out there but in reading them I feel like I am still missing something.
It turns out that what I was trying to do is not possible.
As stated in other places:
A maximum number of backup files when rolling on date/time boundaries is not supported.
Because of this, I took the date portion out so that the backups roll by size only. After doing that I did not have the same issues. I don't like the file name as much but it is still easy enough to track them based on their file properties having the date last edited.

Log4net error: Why Log4net created many log files instead of one log file by program start by using MPI (paralle or multi prozess)

I have a problem with the log output in a single file by using MPI (Message Passing Interface) into my app (write in C#) and log4net. The log output works fine when my app a little time works but when the app start created log4net sometimes not one log file but two or three log files. Here a example:
Properly (App start and log4net build one log file):
Log_2014_02_25_[12.39.07]_Build_2014_02_25
Wrong (App start and log4net build three log files):
Log_2014_02_25_[12.12.03]_Build_2014_02_25
Log_2014_02_25_[12.12.03]_Build_2014_02_252014_02_25
Log_2014_02_25_[12.12.03]_Build_2014_02_252014_02_25252014_02_25
I think log4net tries exactly at the same time to write something in the log file. If that coincidentally happens is the log file locked and log4net cannot in the same log file write. In this case created log4net probably created a new log file. In short, I think the problem is the Minimal Lock from log4net but I'm not sure and not know how I can solve the error.
Here my log4net config:
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs\%property{LogFileName}.log"/>
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy_MM_dd" />
<staticLogFileName value="false" />
<preserveLogFileNameExtension value="true"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd.MM.yyyy HH:mm:ss} - %message%newline" />
</layout>
</appender>
var fileName = string.Format("Log_{0}_[{1}]_Build_",
DateTime.Now.ToString("yyyy_MM_dd"), DateTime.Now.ToString("HH.mm.ss")); //
GlobalContext.Properties["LogFileName"] = fileName;
log4net.Config.XmlConfigurator.Configure();
Thx for all help.... :)
you are using a minimal lock.
try:
<lockingModel type="log4net.Appender.FileAppender+InterProcessLock" />

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.

Need to modify this log4net to write to a file, with ability to write to many files

So I already have nhibernate working which uses log4net, and my web.config currently looks like:
<log4net debug="false">
<appender name="console" type="log4net.Appender.ConsoleAppender, log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n"/>
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default priority -->
<root>
<priority value="INFO"/>
<appender-ref ref="console"/>
</root>
</log4net>
Now my current requirement is the ability to create a seperate log file for each major module that I have in my application.
Right now it seems to be just writing to console, but I need to add the ability to write to files.
What do I have to modify in my configuration to be able to do this?
I want to be able to, in my code, say I want to write to logfile "logfile_1", and if it doesn't exist, create it, otherwise just append to it.
Really simple, rinse and repeat as required for number of files you want, you can also associate namespaces with different files if you want them separated out that way but I find it easier just to use Log2Console to view the file all together.
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="k:\temp\log2console.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.XmlLayoutSchemaLog4j" />
</appender>
Don't forget to add the appender-ref to your root section.

Resources