log4net 写入日志到不同的位置

某些业务需要根据不同的功能将日志记录到不同的位置,以便于区分。

xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="Console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      
      <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>
  
  
  
  
  
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();
    }
}

浏览页面后,可以看到日志目录如下:

log4net 写入日志到不同的位置_第1张图片

 

 

参考资料:https://stackoverflow.com/questions/11930381/log4net-multiple-appenders-writing-to-event-viewer

你可能感兴趣的:(log4net 写入日志到不同的位置)