ASP.NET Core 使用Log4net

admin2024-07-05  24

1. Nuget安装log4net,图里的两个

ASP.NET Core 使用Log4net,第1张

2.项目根目录下添加log4net.config.添加下面的代码:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <!-- This section contains the log4net configuration settings -->
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Log/" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <staticLogFileName value="false" />
      <datePattern value="yyyy-MM-dd'.log'" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date  [%thread]  %-5level  %message%newline" />
      </layout>
    </appender>

    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>

  </log4net>

</configuration>

3. 添加一个logHelper.cs

    public class LogHelper
    {
        private static readonly ILog logger;
        static LogHelper()
        {
            if (logger == null)
            {
                var repository = LogManager.CreateRepository("NETCoreRepository");

                XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

                logger = LogManager.GetLogger(repository.Name, "InfoLogger");
            }
        }

        /// <summary>
        /// 普通日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        public static void Info(string message, Exception exception = null)
        {
            if (exception == null)
                logger.Info(message);
            else
                logger.Info(message, exception);
        }

        /// <summary>
        /// 告警日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        public static void Warn(string message, Exception exception = null)
        {
            if (exception == null)
                logger.Warn(message);
            else
                logger.Warn(message, exception);
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        public static void Error(string message, Exception exception = null)
        {
            if (exception == null)
                logger.Error(message);
            else
                logger.Error(message, exception);
        }
    }

4. 调用:

LogHelper.Info("test Info log");     //普通日志
LogHelper.Warn("test Warn log");      //告警日志
LogHelper.Error("test Error log");   //错误日志

项目里就会生成log文件

ASP.NET Core 使用Log4net,第2张

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!