0
我無法找到關於我正在尋找的信息。基本上需要能夠即時創建日誌文件。詳細地說,我們希望能夠根據某些事件更改日誌文件的位置。log4net動態創建日誌文件
例如: 所以我從C:\ Type1Logs \ Log.txt開始,並正常寫入文件。接下來會出現一個事件,它會要求在C:\ Type2Logs \ Logs.dat中創建的新文件以及發送到該文件的所有新日誌消息。
以下是我用作原型的一些簡單代碼。我添加了hier進行調試,看看我是否可以使用該路線進行更改。它確實讓我發現我現在的代碼創建了另一個appender,而不是改變現有的appender。
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;
}
}
}
看看這個帖子是你在尋找: [log4net的:以編程方式指定多個記錄器(http://stackoverflow.com/ a/308544/2794484) –
[This answer](http://stackoverflow.com/a/6963420/43846)顯示如何更改現有appender上的文件位置 – stuartd
感謝您的鏈接。 Stuartd的是我需要的。有趣的是,我只是在十分鐘前找出答案,當我看到你的評論時即將發佈答案:) –