.Net 6 Log4Net-【.Net Core】
一:
1.NuGet引入程序包:
1.Log4Net 2.Microsoft.Extensions.Logging.Log4Net.AspNetCore
2.准备好配置文件:CfgFile--官网可以下载
3.配置读取文件生效,注册 【Program.cs】
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);//var builder=>update==> WebApplicationBuilder builder { //Nuget引入 //1.Log4Net //2.Microsoft.Extensions.Logging.Log4Net.AspNetCore builder.Logging.AddLog4Net("CfgFile/log4net.Config"); }
注意:修改文件属性
4.注入得到Log4Net实例开始记录日志 新增的控制器【SecondController】
public class SecondController : Controller { //1.定义 private readonly ILogger<SecondController> _logger; private readonly ILoggerFactory _factory; public SecondController(ILogger<SecondController> logger,ILoggerFactory factory) { this._logger = logger; this._logger.LogInformation($"{this.GetType().Name}被构造了:_logger"); this._factory = factory; ILogger<SecondController> _logger1 = _factory.CreateLogger<SecondController>(); _logger1.LogInformation($"{this.GetType().Name}被构造了:_logger1"); } public IActionResult Index() { this._logger.LogInformation($"Index被执行了"); ILogger<SecondController> _logger2 = _factory.CreateLogger<SecondController>(); _logger2.LogInformation($"{this.GetType().Name}被执行了:_logger2"); return View(); } }
这是结果:
二.Log4Net日志写SqlServer
1.Nuget以来程序包引入;
System.Data.SqlClient
2.修改配置文件:支持写数据库日志
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="utf-8"?> <log4net> <!-- Define some output appenders --> <!--Text形式--> <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=.;Initial Catalog=LogManager;Persist Security Info=True;User ID=sa;Password=123456" /> <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"/> <!--root类似路由,level表示支持的记录方式--> <level value="INFO"/> <appender-ref ref="rollingAppender" /> <appender-ref ref="AdoNetAppender_SqlServer" /> </root> </log4net>
3.初始化数据库日志表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* 脚本包含: 1.了Log4Net写数据库日志脚本 2. Nlog写数据库日志脚本 */ USE [master] GO /* 创建数据库LogManager */ CREATE DATABASE [LogManager]; GO ALTER DATABASE [LogManager] SET COMPATIBILITY_LEVEL = 150 GO IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) begin EXEC [LogManager].[dbo].[sp_fulltext_database] @action = 'enable' end GO ALTER DATABASE [LogManager] SET ANSI_NULL_DEFAULT OFF GO ALTER DATABASE [LogManager] SET ANSI_NULLS OFF GO ALTER DATABASE [LogManager] SET ANSI_PADDING OFF GO ALTER DATABASE [LogManager] SET ANSI_WARNINGS OFF GO ALTER DATABASE [LogManager] SET ARITHABORT OFF GO ALTER DATABASE [LogManager] SET AUTO_CLOSE OFF GO ALTER DATABASE [LogManager] SET AUTO_SHRINK OFF GO ALTER DATABASE [LogManager] SET AUTO_UPDATE_STATISTICS ON GO ALTER DATABASE [LogManager] SET CURSOR_CLOSE_ON_COMMIT OFF GO ALTER DATABASE [LogManager] SET CURSOR_DEFAULT GLOBAL GO ALTER DATABASE [LogManager] SET CONCAT_NULL_YIELDS_NULL OFF GO ALTER DATABASE [LogManager] SET NUMERIC_ROUNDABORT OFF GO ALTER DATABASE [LogManager] SET QUOTED_IDENTIFIER OFF GO ALTER DATABASE [LogManager] SET RECURSIVE_TRIGGERS OFF GO ALTER DATABASE [LogManager] SET DISABLE_BROKER GO ALTER DATABASE [LogManager] SET AUTO_UPDATE_STATISTICS_ASYNC OFF GO ALTER DATABASE [LogManager] SET DATE_CORRELATION_OPTIMIZATION OFF GO ALTER DATABASE [LogManager] SET TRUSTWORTHY OFF GO ALTER DATABASE [LogManager] SET ALLOW_SNAPSHOT_ISOLATION OFF GO ALTER DATABASE [LogManager] SET PARAMETERIZATION SIMPLE GO ALTER DATABASE [LogManager] SET READ_COMMITTED_SNAPSHOT OFF GO ALTER DATABASE [LogManager] SET HONOR_BROKER_PRIORITY OFF GO ALTER DATABASE [LogManager] SET RECOVERY FULL GO ALTER DATABASE [LogManager] SET MULTI_USER GO ALTER DATABASE [LogManager] SET PAGE_VERIFY CHECKSUM GO ALTER DATABASE [LogManager] SET DB_CHAINING OFF GO ALTER DATABASE [LogManager] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) GO ALTER DATABASE [LogManager] SET TARGET_RECOVERY_TIME = 60 SECONDS GO ALTER DATABASE [LogManager] SET DELAYED_DURABILITY = DISABLED GO ALTER DATABASE [LogManager] SET ACCELERATED_DATABASE_RECOVERY = OFF GO EXEC sys.sp_db_vardecimal_storage_format N'LogManager', N'ON' GO ALTER DATABASE [LogManager] SET QUERY_STORE = OFF GO USE [LogManager] GO /****** Object: Table [dbo].[Log4Net] Script Date: 2021/11/26 10:56:35 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /* 创建Log4net的表 */ CREATE TABLE [dbo].[Log4Net]( [Id] [int] IDENTITY(1,1) NOT NULL, [Date] [datetime] NOT NULL, [Thread] [varchar](255) NOT NULL, [Level] [varchar](50) NOT NULL, [Logger] [varchar](255) NOT NULL, [Message] [varchar](4000) NOT NULL, [Exception] [varchar](2000) NULL ) ON [PRIMARY] GO /****** Object: Table [dbo].[NLog] Script Date: 2021/11/26 10:56:35 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /* 创建Log4net的表 */ CREATE TABLE [dbo].[NLog]( [Id] [int] IDENTITY(1,1) NOT NULL, [Application] [nvarchar](50) NOT NULL, [Logged] [datetime] NOT NULL, [Level] [nvarchar](50) NOT NULL, [Message] [nvarchar](max) NOT NULL, [Logger] [nvarchar](250) NULL, [Callsite] [nvarchar](max) NULL, [Exception] [nvarchar](max) NULL, CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO USE [master] GO ALTER DATABASE [LogManager] SET READ_WRITE GO
4.注入写日志测试;需要在上面的基础上直接操作
结果:
本文来自博客园,作者:wangwangwangMax,转载请注明原文链接:https://www.cnblogs.com/wangwangwangMax/p/15652704.html