首页 > 编程语言 >Asp.Net Core中使用日志组件log4net

Asp.Net Core中使用日志组件log4net

时间:2022-11-12 22:44:22浏览次数:46  
标签:log4net Core Asp INFO SecondController 2022 11 NET Logger

我们在开发任何项目过程中,记录各种日志是太正常不过的事情。没有日志记录的项目,也不可能放心进入生产环境运行。因此日志的记录,是必须要做的。

在.NET开发中,log4net是个常用的日志组件。本文简单记录下在ASP.NET Core中使用log4net来写日志。

1.Nuget中引入log4net组件

控制台执行以下命令:

Install-Package log4net
Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore

2.在项目根目录下新建log4net的配置文件log4net.config,并将其设置为始终复制。 

项目根目录下创建文件夹CfgFile,在添加XML文件log4net.config

<?xml version="1.0" encoding="utf-8"?>
<log4net>
    <!-- Define some output appenders -->
    <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
        <file value="log4\log.txt" />
        <!--追加日志内容-->
        <appendToFile value="true" />

        <!--防止多线程时不能写Log,官方说线程非安全-->
        <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

        <!--可以为:Once|Size|Date|Composite-->
        <!--Composite为Size和Date的组合-->
        <rollingStyle value="Composite" />

        <!--当备份文件时,为文件名加的后缀-->
        <datePattern value="yyyyMMdd.TXT" />

        <!--日志最大个数,都是最新的-->
        <!--rollingStyle节点为Size时,只能有value个日志-->
        <!--rollingStyle节点为Composite时,每天有value个日志-->
        <maxSizeRollBackups value="20" />

        <!--可用的单位:KB|MB|GB-->
        <maximumFileSize value="3MB" />

        <!--置为true,当前最新日志文件名永远为file节中的名字-->
        <staticLogFileName value="true" />

        <!--输出级别在INFO和ERROR之间的日志-->
        <filter type="log4net.Filter.LevelRangeFilter">
            <param name="LevelMin" value="ALL" />
            <param name="LevelMax" value="FATAL" />
        </filter>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
        </layout>
    </appender>

    <!--SqlServer形式-->
    <!--log4net日志配置:http://logging.apache.org/log4net/release/config-examples.html -->
    <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
        <!--日志缓存写入条数 设置为0时只要有一条就立刻写到数据库-->
        <bufferSize value="0" />
        <connectionType value="System.Data.SqlClient.SqlConnection,System.Data.SqlClient, Version=4.6.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <connectionString value="Data Source=.\SQLEXPRESS;Initial Catalog=LogManager;Persist Security Info=True;User ID=sa;Password=a123456!" />
        <commandText value="INSERT INTO Log4Net ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
        <parameter>
            <parameterName value="@log_date" />
            <dbType value="DateTime" />
            <layout type="log4net.Layout.RawTimeStampLayout" />
        </parameter>
        <parameter>
            <parameterName value="@thread" />
            <dbType value="String" />
            <size value="255" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%thread" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@log_level" />
            <dbType value="String" />
            <size value="50" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%level" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@logger" />
            <dbType value="String" />
            <size value="255" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%logger" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@message" />
            <dbType value="String" />
            <size value="4000" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%message" />
            </layout>
        </parameter>
        <parameter>
            <parameterName value="@exception" />
            <dbType value="String" />
            <size value="2000" />
            <layout type="log4net.Layout.ExceptionLayout" />
        </parameter>
    </appender>
    
    <root>

        <!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->
        <!--OFF:0-->
        <!--FATAL:FATAL-->
        <!--ERROR: ERROR,FATAL-->
        <!--WARN: WARN,ERROR,FATAL-->
        <!--INFO: INFO,WARN,ERROR,FATAL-->
        <!--DEBUG: INFO,WARN,ERROR,FATAL-->
        <!--ALL: DEBUG,INFO,WARN,ERROR,FATAL--> 
        <priority value="ALL"/>
        
        <level value="INFO"/>
        <appender-ref ref="rollingAppender" />
        <appender-ref ref="AdoNetAppender_SqlServer" />
    </root>
</log4net>

3.在Controller中输出日志内容:

public class SecondController : Controller
    {
        private readonly ILogger<SecondController> _Logger;
        private readonly ILoggerFactory _LoggerFactory;
        public SecondController(ILogger<SecondController> logger, ILoggerFactory loggerFactory)
        {
            this._Logger = logger;
            this._Logger.LogInformation($"{this.GetType().Name} 被构造了。。。_Logger");

            this._LoggerFactory = loggerFactory;
            ILogger<SecondController> _Logger2 = this._LoggerFactory.CreateLogger<SecondController>();
            _Logger2.LogInformation($"{this.GetType().Name} 被构造了。。。_Logger2");
        }

        public IActionResult Index()
        {
            ILogger<SecondController> _Logger3 = this._LoggerFactory.CreateLogger<SecondController>();
            _Logger3.LogInformation($"Index 被执行了。。。。。_Logger3");
            this._Logger.LogInformation($"Index 被执行了。。。");
            return View();
        }


        public IActionResult Level()
        { 
            _Logger.LogDebug("this is Debug");
            _Logger.LogInformation("this is Info");
            _Logger.LogWarning("this is Warn");
            _Logger.LogError("this is Error");
            _Logger.LogTrace("this is Trace");
            _Logger.LogCritical("this is Critical");

            return new JsonResult(new { Success = true });
        }


        public object GetData()
        {
            return new
            {
                Id = 123,
                Name = "Richard"
            };
        }
    }

以上配置的log4net,实现了.txt格式日志文件的写入,还有日志写库。

输出日志如下:

2022-11-12 22:29:46,368 [.NET ThreadPool Worker] INFO Advanced.NET6.Project.Controllers.SecondController - SecondController 被构造了。。。_Logger
2022-11-12 22:29:46,377 [.NET ThreadPool Worker] INFO Advanced.NET6.Project.Controllers.SecondController - SecondController 被构造了。。。_Logger2
2022-11-12 22:29:55,460 [.NET ThreadPool Worker] INFO Advanced.NET6.Project.Controllers.SecondController - Index 被执行了。。。。。_Logger3
2022-11-12 22:29:55,465 [.NET ThreadPool Worker] INFO Advanced.NET6.Project.Controllers.SecondController - Index 被执行了。。。

执行以下SQL语句,查询下写入库中的日志:

select * from log4net order by Date desc

得到如下的数据列表:

Id Date Thread Level Logger Message Exception
1009 2022-11-12 22:29:55.467 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController Index 被执行了。。。
1008 2022-11-12 22:29:55.460 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController Index 被执行了。。。。。_Logger3
1007 2022-11-12 22:29:46.377 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController SecondController 被构造了。。。_Logger2
1006 2022-11-12 22:29:46.370 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController SecondController 被构造了。。。_Logger
1004 2022-11-12 22:28:46.443 1 INFO Microsoft.Hosting.Lifetime Hosting environment: Development
1003 2022-11-12 22:28:46.437 1 INFO Microsoft.Hosting.Lifetime Application started. Press Ctrl+C to shut down.
1002 2022-11-12 22:28:46.160 1 INFO Microsoft.Hosting.Lifetime Now listening on: http://localhost:5999
8 2022-11-11 09:55:40.147 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController Index 被执行了。。。
7 2022-11-11 09:55:40.140 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController Index 被执行了。。。。。_Logger3
6 2022-11-11 09:55:37.507 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController SecondController 被构造了。。。_Logger2
5 2022-11-11 09:55:37.493 .NET ThreadPool Worker INFO Advanced.NET6.Project.Controllers.SecondController SecondController 被构造了。。。_Logger
3 2022-11-11 09:55:25.780 1 INFO Microsoft.Hosting.Lifetime Hosting environment: Development
2 2022-11-11 09:55:25.773 1 INFO Microsoft.Hosting.Lifetime Application started. Press Ctrl+C to shut down.
1 2022-11-11 09:55:25.630 1 INFO Microsoft.Hosting.Lifetime Now listening on: http://localhost:5999

 

log4net的使用,就这样完事啦...

 

标签:log4net,Core,Asp,INFO,SecondController,2022,11,NET,Logger
From: https://www.cnblogs.com/michael999/p/16884922.html

相关文章