.net core 项目使用log4net

引入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文件下

 

posted @ 2024-11-05 10:48  路边有一棵草  阅读(14)  评论(0编辑  收藏  举报