某些業務須要根據不一樣的功能將日誌記錄到不一樣的位置,以便於區分。app
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<!-- Pattern to output the caller's file name and line number -->
<conversionPattern value="%5level [%thread] (%file:%line) - %date - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs\\Common\\%date{yyyy-MM-dd}.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1KB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="EventLoggerAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs\\Events\\%date{yyyy-MM-dd}.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1KB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<logger name="FileLogger">
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</logger>
<logger name="EventLogger">
<level value="ALL" />
<appender-ref ref="EventLoggerAppender" />
</logger>
<!-- <root> -->
<!-- <level value="DEBUG" /> -->
<!-- <appender-ref ref="RollingLogFileAppender" /> -->
<!-- <appender-ref ref="Console" /> -->
<!-- </root> -->
</log4net>
日誌工具類(這裏只是簡單的封裝):工具
public static class LogHelper { private static readonly ILog logger = LogManager.GetLogger("FileLogger"); private static readonly ILog eventLogger = LogManager.GetLogger("EventLogger"); static LogHelper() {
log4net.Config.XmlConfigurator.Configure(new FileInfo(HttpContext.Current.Server.MapPath("~/log4net.config"))); } public static void Error(string errMessage) { logger.Error(errMessage); } public static void LogEvent(string errMessage) { eventLogger.Error(errMessage); } }
public class HomeController : Controller { public ActionResult Index() { LogHelper.Error("出錯啦");
LogHelper.LogEvent("fafdsafdsaff"); ViewBag.Title = "Home Page"; return View(); } }
瀏覽頁面後,能夠看到日誌目錄以下:spa
參考資料:https://stackoverflow.com/questions/11930381/log4net-multiple-appenders-writing-to-event-viewer日誌