log4net FileAppender
類不提供BufferSize
屬性,因此無法直接在配置中或使用該擴展方法對其進行設置。 (該屬性僅由BufferingAppenderSkeleton
基類暴露,但不屬於FileAppender
類的基類)。
實際上,在log4net代碼庫中進行探測,看起來好像您可以控制FileAppender
所使用的緩衝區大小的唯一方法是編寫您自己的LockingModelBase
實現。附帶log4net的那些實現,即ExclusiveLock
或MinimalLock
,內部使用一個FileStream
構造,使用的爲0x1000默認的緩衝區大小,即4096
有了這樣說,你也許能夠做這樣的事情:
.Log4Net<RollingFileAppender>(x=>
{
x.AppendToFile = true;
x.Threshold = Level.Debug;
x.MaxSizeRollBackups = 10;
x.RollingStyle = RollingFileAppender.RollingMode.Size;
x.File = "c:\\Logs\\log.txt";
x.LockingModel = new MyUnbufferedLockingModel();
})
隨着MyUnbufferedLockingModel
是這樣的:
public class MyUnbufferedLockingModel : log4net.FileAppender.LockingModelBase
{
// This is essentially a rip-off of the default 'ExclusiveLock' class,
// but when creating the "m_stream", using an explicit buffer size of 1.
// Depending on your needs you may want to use the 'MinimalLock' class
// instead.
private Stream m_stream = null;
public override Stream AcquireLock()
{
return m_stream;
}
public override void CloseFile()
{
using (CurrentAppender.SecurityContext.Impersonate(this))
{
m_stream.Close();
}
}
public override void OpenFile(string filename, bool append, Encoding encoding)
{
try
{
using (CurrentAppender.SecurityContext.Impersonate(this))
{
string directoryName = Path.GetDirectoryName(filename);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
FileMode mode = append ? FileMode.Append : FileMode.Create;
m_stream = new FileStream(filename, mode, FileAccess.Write,
FileShare.Read,
1 /*BufferSize*/);
}
}
catch (Exception exception)
{
CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + exception.Message);
}
}
public override void ReleaseLock()
{
}
}
謝謝你的創意答案。你最終指出我的答案,所以我會給你信貸。我還會用我的工作解決方案爲問題創建另一個答案。 – Patrick 2012-03-02 16:23:44
謝謝:-)你應該也接受你自己的答案作爲正確的答案。 – 2012-03-05 05:17:52