. NET learning notes - about NET Core [. netcore project structure and use of Log4Net and NLog]

Posted by aneuryzma on Thu, 20 Jan 2022 09:15:31 +0100

1, A NET Core project structure

1.Properties: some configurations required for project startup: including port number and IP address
2.wwwroot: js/css/js package
3.MVC ---- model control
①. Controller: Controller - responsible for business logic calculation
②. Presentation layer: used to display various results and interact with users
③. Model: concatenated between C – V to save data
4.appsettings: configuration file
5.Program console - ASP NET Core5. 0 is essentially a console
6.Startup: supports some related configurations for website operation

2, Pass value to page

base represents the alias of the parent class (Controller)

1.ViewBag

base.ViewBag.User1 = "Zhang San";

2.ViewData

base.ViewData["User2"] = "Li Si";

3.TempData

base.TempData["User3"] = "Wang Er Ma Zi";

4.HttpContext.Session.SetString

Configuration is required to use Session
1. You need to add a reference in the view: @ using Microsoft AspNetCore. Http
2. In the ConfigureServices method in startup, add: services AddSession();
3. Add: app. In the Configure method in startup UseSession();

base.HttpContext.Session.SetString("User4", "Zhao Si'er");

Configuration presentation:
Index. In cshtml:

Startup. In CS:

5.return View();

Because of method overloading, the value passed in by View() can only be of object type, and the passed in string type will be automatically regarded as the passed in View name

object User5 = "Liu liuer";
return View(User5);

Values on the page:

@using Microsoft.AspNetCore.Http

@{
   <h3>User1=@base.ViewBag.User1 </h3>
   <h3>User2=@base.ViewData["User2"]</h3>
   <h3>User3=@base.TempData["User3"]</h3>
   <h3>User4=@base.Context.Session.GetString("User4")</h3>
   <h3>User5=@Model</h3>
}

Effect of operation:

Supplement:
①. The internal implementation of ViewBag is the same as that of ViewData. Both are dictionary supported. If the key is the same, the value of the latter will overwrite the value of the former, such as:

base.ViewBag.User1 = "Zhang San";  
base.ViewData["User1"] = "Zhang San~~Zhang San"; 

When the key is User1, the final running result is Zhang San ~ ~ Zhang San

②. The value transfer methods available for cross page value transfer are
TempData
The essence is to save the value to the server memory, but the value can only be taken once after assignment. After assignment in a controller, the value can only be taken in one view. After taking the value once, the value can not be taken again

HttpContext.Session.SetString
The essence is that the value is saved in the server memory and can be accessed at will after assignment

3, Configuration log

>>>>>>>>>>>>>>>>>>>>>>>>>>>>NLog log -- file record:<<<<<<<<<<<<<<<<<<<<<<<<<<<
Step 1: install NuGet package

Right click on the solution and select the NuGet package that manages the solution

Switch to browse and enter NLog in the find box Web. Aspnetcore, select the package, select all items, and click Install

Enter NLog. In the search box Config, select all items and click Install

After successful installation, an NLog will be added to the project config


Step 2: about NLog config

NLog. The config file is locked and cannot be modified by default, so you need to copy it out and overwrite it after modification

<targets>
		<!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->
		<!--type:File type of record name:name fileName:Full path/name layout:Record text-->
		<target xsi:type="File" name="allfile" fileName = "Log\nlog-all-${shortdate}.log" layout="${longdata}|${logger}|${uppercase:${level}}|${message} ${exception}" />
		<target xsi:type="File" name="ownFile-web" fileName = "Log\nlog-my-${shortdate}.log" layout="${longdata}|${logger}|${uppercase:${level}}|${message} ${exception}" />
		<!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
	</targets>
	<!--Used to choose where to write it down-->
	<rules>
		<!-- add your logging rules here -->
		<!--minlevel:Log minimum level writeTo:Log to write name(above targets Defined)-->
		<!--If the minimum log level is Trace Then write targets in name by allfile In the log-->
		<logger name="*" minlevel="Trace" writeTo="allfile"/>
		<!--If set final,When this route is matched, the route below this route will not be executed. If it is not matched, it will continue to match below-->
		<logger name="Microsoft.*" minlevel="Trace" final="true"/>
		<!--The upper route filters all Microsoft.*Log, so only print here Microsoft.*Logs other than-->
		<logger name="*" minlevel="Trace" writeTo="ownFile-web"/>
		<!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
	</rules>

Step 3: Implementation (Program.cs)

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace NET5WebApplication
{
	public class Program
	{
		public static void Main(string[] args)
		{
			//Reference using NLog Web;  Namespace
			//Incoming NLog Config path. For example, if it is placed in a folder, it is nlogbuilder Configurenlog ("folder name / NLog.config");
			NLogBuilder.ConfigureNLog("NLog.config");

			CreateHostBuilder(args).Build().Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup<Startup>();
				})
				//About NLog configuration
				.ConfigureLogging(logging => { 
					logging.ClearProviders();//Delete all other log related configurations
					logging.SetMinimumLevel(LogLevel.Trace);//Set the minimum log level to Trace, corresponding to NLog Settings in < Rules > tab in config
				}).UseNLog()
				;
	}
}

Step 4: call

Test NLog with constructor in controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace NET5WebApplication.Controllers
{
	public class FirstController : Controller
	{

		private readonly ILogger<FirstController> _ILogger = null;

		private readonly ILoggerFactory _ILoggerFactory = null;

		//Test NLog using constructor
		public FirstController(ILogger<FirstController> iLogger, ILoggerFactory iLoggerFactory)
		{
			_ILogger = iLogger;
			_ILogger.LogInformation("_ILogger:" + this.GetType().FullName + "Constructed");

			_ILoggerFactory = iLoggerFactory;
			ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
			_ILogger2.LogInformation($"_ILogger2: {this.GetType().FullName} Constructed");
		}

		public IActionResult Index()
		{
			base.ViewBag.User1 = "Zhang San";

			return View();
		}
	}
}

Step 5: results

The generated path and name are the same as ours in NLog The targets in config are consistent with those defined in the targets tag


File content and NLog Config, nlog-my-2022-01-18 After the log is filtered by a layer of routing, all nlog-all-2022-01-18 Microsoft. Log The first log information is filtered

>>>>>>>>>>>>>>>>>>>>>>>>>>>>NLog log -- database record (SqlServer as an example):<<<<<<<<<<<<<<<<<<<<<<<<<<<
Step 1: install NuGet package

Right click on the solution and select the NuGet package that manages the solution

Switch to browse and enter Microsoft. Com in the find box Data. SqlClient, select the package (remember to install version 3.0.0), select all items, and click Install

Step 2: change NLog Config file

Add code in targets tag

<!--connect SQLServer database-->
<!--commandText: to NLogManager Add the following fields to the table-->
<target name="AllDatabase" xsi:type="Database"
		dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
		connectionString="Data Source=database IP address;Initial Catalog=Database name;Persist Security Info=True;User ID=user name;Password=password;"
		commandText="insert into dbo.NLogManager (Application, Logged, Level, Message,Logger, CallSite, Exception) values (@Application, @Logged, @Level, @Message,@Logger, @Callsite, @Exception);">
	<parameter name="@application" layout="AspNetCoreNlog" />
	<parameter name="@logged" layout="${date}" />
	<parameter name="@level" layout="${level}" />
	<parameter name="@message" layout="${message}" />
	<parameter name="@logger" layout="${logger}" />
	<parameter name="@callSite" layout="${callsite:filename=true}" />
	<parameter name="@exception" layout="${exception:tostring}" />
</target>

Add code to the rules tab

  <logger name="*" minlevel="Trace" writeTo="AllDatabase" />

Script to create the table used above the database

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[NLogManager] (
    [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) ON [PRIMARY]
) ON [PRIMARY]

Step 3: Implementation (Program.cs)

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace NET5WebApplication
{
	public class Program
	{
		public static void Main(string[] args)
		{
			//Reference using NLog Web;  Namespace
			//Incoming NLog Config path. For example, if it is placed in a folder, it is nlogbuilder Configurenlog ("folder name / NLog.config");
			NLogBuilder.ConfigureNLog("NLog.config");

			CreateHostBuilder(args).Build().Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup<Startup>();
				})
				//About NLog configuration
				.ConfigureLogging(logging => { 
					logging.ClearProviders();//Delete all other log related configurations
					logging.SetMinimumLevel(LogLevel.Trace);//Set the minimum log level to Trace, corresponding to NLog Settings in < Rules > tab in config
				}).UseNLog()
				;
	}
}

Step 4: call

Test NLog with constructor in controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace NET5WebApplication.Controllers
{
	public class FirstController : Controller
	{

		private readonly ILogger<FirstController> _ILogger = null;

		private readonly ILoggerFactory _ILoggerFactory = null;

		//Test NLog using constructor
		public FirstController(ILogger<FirstController> iLogger, ILoggerFactory iLoggerFactory)
		{
			_ILogger = iLogger;
			_ILogger.LogInformation("_ILogger:" + this.GetType().FullName + "Constructed");

			_ILoggerFactory = iLoggerFactory;
			ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
			_ILogger2.LogInformation($"_ILogger2: {this.GetType().FullName} Constructed");
		}

		public IActionResult Index()
		{
			base.ViewBag.User1 = "Zhang San";

			return View();
		}
	}
}

Step 5: results

PS: you can also use system Data. SqlClient package is used for database writing. Compared with the above, the places that need to be changed are: 1 Reference system Data. SqlClient package. 2.NLog. The dbProvider attribute in config needs to be replaced with
dbProvider = "System.Data.SqlClient", consistent elsewhere



>>>>>>>>>>>>>>>>>>>>>>>>>>>>Log4net logging<<<<<<<<<<<<<<<<<<<<<<<<<<<
Step 1: install NuGet package

log4net
Microsoft.Extensions.Logging.Log4Net.AspNetCore


Step 2: modify the configuration file
Right click on the project → add → new item → Web configuration file → change the name to log4net Config

Paste in Code:

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

		<!--Prevent writing when multithreading Log,Officials say threads are unsafe-->
		<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

		<!--Can be:Once|Size|Date|Composite-->
		<!--Composite by Size and Date Combination of-->
		<rollingStyle value="Composite" />

		<!--When backing up files,Suffix the file name-->
		<datePattern value="yyyyMMdd.TXT" />

		<!--Maximum number of logs,They are all the latest-->
		<!--rollingStyle Node is Size Time,Only value Logs-->
		<!--rollingStyle Node is Composite Time,Every day value Logs-->
		<maxSizeRollBackups value="20" />

		<!--Available units:KB|MB|GB-->
		<maximumFileSize value="3MB" />

		<!--Set as true,The current latest log file name is always file Name in section-->
		<staticLogFileName value="true" />

		<!--Output level in INFO and ERROR Logs between-->
		<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>
	<root>
		<priority value="ALL"/>
		<level value="ALL"/>
		<appender-ref ref="rollingAppender" />
	</root>
</log4net>

Change the profile property to always copy


Step 3: Implementation (Program.cs)

//About Log4Net configuration
.ConfigureLogging(logging => {
	logging.ClearProviders();//Delete all other log related configurations
	logging.SetMinimumLevel(LogLevel.Trace);//Set the minimum log level to Trace, corresponding to NLog Settings in < Rules > tab in config
	logging.AddLog4Net("log4net.Config");//If it is placed in a folder, it is logging Addlog4net ("folder name / log4net.Config");
})

Step 4: call

Test NLog with constructor in controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace NET5WebApplication.Controllers
{
	public class FirstController : Controller
	{

		private readonly ILogger<FirstController> _ILogger = null;

		private readonly ILoggerFactory _ILoggerFactory = null;

		//Test log using constructor
		public FirstController(ILogger<FirstController> iLogger, ILoggerFactory iLoggerFactory)
		{
			_ILogger = iLogger;
			_ILogger.LogInformation("_ILogger:" + this.GetType().FullName + "Constructed");

			_ILoggerFactory = iLoggerFactory;
			ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
			_ILogger2.LogInformation($"_ILogger2: {this.GetType().FullName} Constructed");
		}

		public IActionResult Index()
		{
			base.ViewBag.User1 = "Zhang San";

			return View();
		}
	}
}

Step 5: results

Topics: .NET log4net