我已经为 log4net 实现了一个自定义附加程序,我正在其中记录到文件并发送邮件。我想为每种情况记录不同的消息字符串。下面的代码在文件中创建了两个日志条目,一个带有附加字符串,一个没有附加字符串。它还发送没有附加字符串的电子邮件。
public static void Log(this ILog log, Level level, string message)
{
var token = string.Format("{0},{1},{2}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, level, message);
int count = _tokenTimeThrottler.CheckAllow(token);
if (count >= 0)
{
//only to file logger, with an appended string
log = LogManager.GetLogger("LogFileAppender");
log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, level, count <= 1 ? message : count + " counts of: " + message, null);
}
//only to mail
log = LogManager.GetLogger("MyMailAppender");
log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, level, message, null);
}
但我不想在我做的时候登录到文件。
//only to mail
log = LogManager.GetLogger("MyMailAppender");
log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, level, message, null);
我的配置文件,一个附加程序是使用配置文件添加的,另一个附加程序是一个 dll,所以它是在运行时添加的。
第一个附加程序:
<log4net>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\git\logs\log.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %m%n" />
</layout>
</appender>
</log4net>
第二个附加程序(在运行时添加):
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
PatternLayout patternLayout = new PatternLayout { ConversionPattern = "%d [%t] %-5p %m%n" };
MyMailAppender myAppender = new MyMailAppender
{
Name = "MyMailAppender",
Layout = patternLayout,
Access = "ghjkgj",
Threshold = Level.Info,
};
myAppender .ActivateOptions();
hierarchy.Root.AddAppender(myAppender );
hierarchy.Root.Level = Level.All;
hierarchy.Configured = true;