I couldnt find a post about what I am looking to do. Basically the requirement is to be able to create log files on the fly. In detail we want to be able to change the location of the log file based on certain events.
Example: So I start with C:\Type1Logs\Log.txt and write to the file normally. Next an event comes along that will want a new file created at C:\Type2Logs\Logs.dat and all new log messages sent to that file instead.
Here is some simple code I am using as a prototype. I added hier to debug and see if I can change it using that route. It did enable me to find out that my current code creates another appender rather than changing the existing one.
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsoleApp
{
class Program
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
string Input = "";
Logger.ConfigureFileAppender("log.txt"); // This only has to be called once.
while (Input.ToUpper() != "QUIT")
{
Console.WriteLine("Enter text to write to the log");
Input = Console.ReadLine();
if (Input.Length > 7 && Input.ToUpper().Substring(0,6) == "NEWLOG")
{
Logger.ConfigureFileAppender(Input.Substring(6));
Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy;
}
Log.Info(Input);
}
}
}
class Logger
{
public static void ConfigureFileAppender(string logFile)
{
var fileAppender = GetFileAppender(logFile);
BasicConfigurator.Configure(fileAppender);
((Hierarchy)LogManager.GetRepository()).Root.Level = Level.Debug;
}
private static IAppender GetFileAppender(string logFile)
{
var layout = new PatternLayout("%date %-5level %logger - %message%newline");
layout.ActivateOptions(); // According to the docs this must be called as soon as any properties have been changed.
var appender = new FileAppender
{
File = logFile,
Encoding = Encoding.UTF8,
Threshold = Level.Debug,
Layout = layout
};
appender.ActivateOptions();
return appender;
}
}
}