如何使用log4net不用多說,這里說一下Repository的用法。log4net Repository代表了倉庫的含義,可以生產(chǎn)多個具名log對象摆寄。這些對象可分別寫入日志。
創(chuàng)建Repository的方法
LogManager.CreateRepository(domain);
Repository的配置
有兩種方法坯门,一種是配置文件微饥,一種是手動寫代碼配置。
手動代碼:
public void InitLog4netConfig3()
{
var infoFilter = new LevelRangeFilter();
infoFilter.LevelMax = log4net.Core.Level.Info;
infoFilter.LevelMin = log4net.Core.Level.Info;
infoFilter.ActivateOptions();
string layoutFormat = "@Log Begin%newlineThread ID:[%thread]%newline%message%newlineLog End@%newline";
var basepath = AppDomain.CurrentDomain.BaseDirectory;
var LogDir = Path.Combine(basepath, "log");
PatternLayout layout = new PatternLayout(layoutFormat);
var domain = "base";
var repository = log4net.LogManager.CreateRepository(domain);
repository.Threshold = Level.Info;
var fileAppender = new RollingFileAppender();
fileAppender.Name = domain + "_" + "Info" + "_FileAppender";
fileAppender.File = System.IO.Path.Combine(LogDir, "Log_" + domain + "\\" + "Info" + "\\");
fileAppender.AppendToFile = true;
fileAppender.RollingStyle = RollingFileAppender.RollingMode.Date;
fileAppender.DatePattern = "yyyy-MM-dd'.log'";
fileAppender.StaticLogFileName = false;
fileAppender.Layout = layout;
fileAppender.AddFilter(infoFilter);
fileAppender.ActivateOptions();
BasicConfigurator.Configure(repository, fileAppender);
}
配置文件:
<log4net>
<root>
<level value="WARN" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
<logger name="log1">
<level value="DEBUG"/>
</logger>
<logger name="log2">
<level value="DEBUG"/>
</logger>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
<param name="File" value="your-log-file.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header] "/>
<param name="Footer" value="[Footer] "/>
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="WARN" />
</filter>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
</log4net>
然后
public void InitLog4netConfig()
{
var domain = "base";
var repository = log4net.LogManager.CreateRepository(domain);
var basepath = AppDomain.CurrentDomain.BaseDirectory;
var filepath = System.IO.Path.Combine(basepath, "log4net.xml");
var fileInfo = new FileInfo(filepath);
XmlConfigurator.Configure(repository, fileInfo);
}
root是所有l(wèi)og的基本配置古戴,其他的log都繼承自root欠橘。level定義了可訪問的最低級別。
問題是log4net只提供了Info(),Warn(),Error()三個接口來寫入日志允瞧。如果我們要單獨(dú)寫入其他級別的日志简软,比如NOTICE蛮拔,該如何實(shí)現(xiàn)呢?
其他級別日志
首先痹升,appender設(shè)置成不同的輸出目錄建炫,F(xiàn)ilter采用LevelRangeFilter并限定好,確保該級別日志會被輸出疼蛾。
其次肛跌,調(diào)整好Repository.Threshold,不要被阻擋在外察郁。
然后衍慎,這么做:
log4net.ILog log = log4net.LogManager.GetLogger("base", "abc");
var loggingEventData = new LoggingEventData()
{
Level = Level.Notice,
Message = "put notice message"
};
log.Logger.Log(new LoggingEvent(loggingEventData));
log.Logger.Log(typeof(LogImpl), Level.Notice, "put notice message 2", null);
- Filter
關(guān)于Filter,LevelMatchFilter并不像其字面含義皮钠,在匹配時才輸出日志稳捆。其真正作用,是在level匹配時麦轰,配合AcceptOnMatch=false阻止后續(xù)Filter的執(zhí)行乔夯。
從反編譯的源代碼可以看出這一點(diǎn):
// AppenderSkeleton.cs
protected virtual bool FilterEvent(LoggingEvent loggingEvent)
{
if (!this.IsAsSevereAsThreshold(loggingEvent.Level))
return false;
IFilter filter = this.FilterHead;
while (filter != null)
{
switch (filter.Decide(loggingEvent))
{
case FilterDecision.Deny:
return false;
case FilterDecision.Neutral:
filter = filter.Next;
break;
case FilterDecision.Accept:
filter = (IFilter) null;
break;
}
}
return true;
}
// LevelMatchFilter.cs
public override FilterDecision Decide(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
throw new ArgumentNullException("loggingEvent");
if (this.m_levelToMatch != (Level) null && this.m_levelToMatch == loggingEvent.Level)
return this.m_acceptOnMatch ? FilterDecision.Accept : FilterDecision.Deny;
else
return FilterDecision.Neutral;
}
- level
如何定義自己的Level呢? 比如說慢日志款侵,也很簡單末荐。
class SlowLogExample
{
private Level SLOW = new Level(Level.Info.Value + 1, "SLOW");
public void InitLogConfig()
{
var InfoFilter = new LevelRangeFilter();
InfoFilter.LevelMax = SLOW;
InfoFilter.LevelMin = SLOW;
InfoFilter.ActivateOptions();
string layoutFormat = "@Log Begin%newlineThread ID:[%thread]%newline%message%newlineLog End@%newline";
var basepath = AppDomain.CurrentDomain.BaseDirectory;
var LogDir = Path.Combine(basepath, "log");
PatternLayout layout = new PatternLayout(layoutFormat);
var domain = "base";
var repository = log4net.LogManager.CreateRepository(domain);
//repository.Threshold = Level.Info;
repository.LevelMap.Add(SLOW);
var fileAppender1 = new RollingFileAppender();
fileAppender1.Name = domain + "_" + "Info" + "_FileAppender";
fileAppender1.File = System.IO.Path.Combine(LogDir, "Log_" + domain + "\\" + "Slow" + "\\");
fileAppender1.AppendToFile = true;
fileAppender1.RollingStyle = RollingFileAppender.RollingMode.Date;
fileAppender1.DatePattern = "yyyy-MM-dd'.log'";
fileAppender1.StaticLogFileName = false;
fileAppender1.Layout = layout;
fileAppender1.AddFilter(InfoFilter);
fileAppender1.ActivateOptions();
BasicConfigurator.Configure(repository, fileAppender1);
}
public void LogSlow(string message)
{
var log = log4net.LogManager.GetLogger("base", "");
log.Logger.Log(typeof(LogImpl), SLOW, message, null);
}
}