.net core 專案使用log4net

路边有一棵草發表於2024-11-05

引入nuget包

1.增加一個log4Net.config的檔案

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
    <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <!--指定日記記錄方式,以滾動檔案的方式(檔案記錄)-->
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
        <!--日誌路徑-->
        <file value="log\" />
        <!--是否是向檔案中追加日誌-->
        <appendToFile value="true" />
        <!--log保留天數-->
        <param name= "MaxSizeRollBackups" value= "10"/>
        <!--每個檔案最大3M-->
        <param name="maximumFileSize" value="3MB" />
        <!--日誌根據日期滾動-->
        <param name="RollingStyle" value="Date" />
        <!--日誌檔名格式為:logs_20230431.log-->
        <param name="DatePattern" value="&quot;logs_&quot;yyyyMMdd&quot;.log&quot;" />
        <!--日誌檔名是否是固定不變的-->
        <param name="StaticLogFileName" value="false" />
        <!--佈局-->
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
        </layout>
    </appender>
    <root>
        <level value="ALL"/>
        <appender-ref ref="DebugAppender" />
        <appender-ref ref="RollingFile" />
    </root>
</log4net>

2.在program.cs中增加這段程式碼

.ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .ConfigureLogging((hostingContext, builder) =>
                     {
                         //該方法需要引入Microsoft.Extensions.Logging名稱空間
                         builder.AddFilter("System", LogLevel.Error); //過濾掉系統預設的一些日誌
                         builder.AddFilter("Microsoft", LogLevel.Error);//過濾掉系統預設的一些日誌

                         //新增Log4Net
                         var path = Path.Combine(Directory.GetCurrentDirectory(), "Log4net.config");
                         //不帶引數,表示:log4net.config的配置檔案就在應用程式的根目錄下,可以指定配置檔案的路徑
                         //新增nuget包,Microsoft.Extensions.Logging.Log4Net.AspNetCore
                         builder.AddLog4Net(path);
                     });
                });

3.增加幫助類

ILogHelper.cs

  /// <summary>
    /// 日誌工具介面類
    /// </summary>
    public interface ILogHelper
    {
        public void LogErr(string throwMsg, Exception ex);
        public void LogErr(string errkey, string errmsg);
        public void LogInfo(string key, string msg);
        public void LogInfo(string msg);
    }

Log4NetHelper.cs

/// <summary>
    /// log4net日誌初始化 這裡就讀取多個配置節點
    /// </summary>
    public static class Log4NetHelper
    {
        private static readonly ILog _logError = LogManager.GetLogger(Assembly.GetCallingAssembly(), "LogError");
        private static readonly ILog _logNormal = LogManager.GetLogger(Assembly.GetCallingAssembly(), "LogNormal");
        private static readonly ILog _logAOP = LogManager.GetLogger(Assembly.GetCallingAssembly(), "LogAOP");

        public static void LogErr(string info, Exception ex)
        {
            if (_logError.IsErrorEnabled)
            {
                _logError.Error(info, ex);
            }
        }
        public static void LogErr(string message)
        {
            if (_logError.IsErrorEnabled)
            {
                _logError.Error(message);
            }
        }

        public static void LogNormal(string info)
        {
            if (_logNormal.IsInfoEnabled)
            {
                _logNormal.Info(info);
            }
        }

        public static void LogAOP(string key, string info)
        {
            if (_logAOP.IsInfoEnabled)
            {
                _logAOP.Info($"{key}:{info}");
            }
        }
        public static void LogAOP(string info)
        {
            if (_logAOP.IsInfoEnabled)
            {
                _logAOP.Info(info);
            }
        }
    }

LogHelper.cs

/// <summary>
    /// 日誌工具實現類
    /// </summary>

    public class LogHelper : ILogHelper//<T>
    {
        private readonly ILogger _logger;

        public LogHelper(ILogger<LogHelper> logger)
        {
            _logger = logger;
        }

        public void LogErr(string throwMsg, Exception ex)
        {

            var errorMsg =
                $"【丟擲資訊】:{throwMsg} \r\n<br/>【異常型別】:{ex.GetType().Name} \r\n<br/>【異常資訊】:{ex.Message} \r\n<br/>【堆疊呼叫】:\r\n<br/>{ex.StackTrace}\r\n<br/>【堆疊呼叫】:\r\n<br/>{ex.ToString()}";
            _logger.LogError(errorMsg);


        }
        public void LogErr(string errkey, string errmsg)
        {
            _logger.LogError(errkey + ":" + errmsg);
        }
        public void LogInfo(string key, string msg)
        {

            _logger.LogInformation(key + ":" + msg);


        }
        public void LogInfo(string msg)
        {
            _logger.LogInformation(msg);

        }
    }

可以這樣使用

Log4NetHelper.LogNormal(@$"讀取失敗,丟擲異常:{ex.Message}{Environment.NewLine}堆疊跟蹤:{ex.StackTrace}");

日誌存放路徑在bin檔案下

相關文章