Reputation: 1845
I develop an application which does something each time in several runs.
I got much logging information in each run. So when a run was successfull (no exceptions thrown), and the users starts a new run, I want to overwrite the log file on starting the new run.
How can I achieve that?
Furthermore: How do I get the log-file name out of the Logger interface? I don't want to parse the App.xaml.cs
Upvotes: 0
Views: 940
Reputation: 1845
The solution is:
public static void StartNewLogFile()
{
Hierarchy hierachy = (Hierarchy)log4net.LogManager.GetRepository();
Logger logger = hierachy.Root;
var rootAppender = logger.Appenders.OfType<FileAppender>().FirstOrDefault();
string filename = rootAppender != null ? rootAppender.File : string.Empty;
while (logger != null)
{
foreach (IAppender appender in logger.Appenders)
{
FileAppender fileAppender = appender as FileAppender;
if (fileAppender != null)
{
fileAppender.File = filename + "a";
fileAppender.File = filename;
fileAppender.ActivateOptions();
}
}
logger = logger.Parent;
}
File.Delete(filename + "a");
}
With a big help from: Programatically force a new log file with Log4Net
Upvotes: 0
Reputation: 73253
To overwrite the log file, use a FileAppender and set appendToFile to false
:
appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<appendToFile value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] .. etc .. />
</layout>
</appender>
However this will not be able to know if your run was successful, and will overwrite the file each time the app is run.
Upvotes: 2