欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

log4net 写入日志到不同的位置

程序员文章站 2022-04-28 09:37:19
某些业务需要根据不同的功能将日志记录到不同的位置,以便于区分。 日志工具类(这里只是简单的封装): 浏览页面后,可以看到日志目录如下: 参考资料:https://*.com/questions/11930381/log4net-multiple-appenders-writi ......

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

<?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();
    }
}

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

log4net 写入日志到不同的位置

 

 

参考资料: