当前位置:网站首页>Help documents on log4net and NLog usage
Help documents on log4net and NLog usage
2022-04-22 07:16:00 【Caramel macchiato】
NLog and Log4Net Use
One 、NLog– Log text
1.Nuget Import assembly
NLog.Web.AspNetCore Logging driver
NLog.Config The configuration file
2. Modify the configuration file
Be careful : This kind of default configuration file , Is read-only , I copied it , It's revised , Then replace it with
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!--Optional, add some variables
Optional , Add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
See https://github.com/nlog/nlog/wiki/Configuration-file
Information about custom logging rules and output .
-->
<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.
Add your goal here
See https://github.com/nlog/NLog/wiki/Targets Look for possible targets .
See https://github.com/nlog/NLog/wiki/Layout-Renderers For possible layout renderers .
-->
<!--
The same is to write the file to the log , The content written is different ,
The difference is layout Property . There are differences in the number of logs written , The difference is reflected in the routing logic
-->
<target xsi:type="File" name="allfile" fileName="Log\nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="ownFile-web" fileName="Log\nlog-my-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="Null" name="blackhole" />
<!--
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}" />
-->
<!-- Configuration is written to the database -->
<!-- Remarks:
The appsetting layouts require the NLog.Extended assembly.
The aspnet-* layouts require the NLog.Web assembly.
The Application value is determined by an AppName appSetting in Web.config.
The "NLogDb" connection string determines the database that NLog write to.
The create dbo.Log script in the comment below must be manually executed.
appsetting The layout needs NLog.Extended Assembly .
aspnet-* The layout needs NLog.Web Assembly .
The application value is determined by Web.config Medium AppName appSetting determine .
“NLogDb” The connection string determines NLog Write to the database .
The... In the following comments must be performed manually create dbo.Log Script .
Script for creating the dbo.Log table.
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] -->
<target name="AllDatabase" xsi:type="Database"
dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
connectionString="Data Source=DESKTOP-VUL99EF;Initial Catalog=CustomerDB;Persist Security Info=True;User ID=sa;Password=sa123;"
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>
</targets>
<rules>
<!-- add your logging rules here -->
<!-- Write to database -->
<logger name="*" minlevel="debug" writeTo="AllDatabase" />
<!-- Routing order will affect log printing . Route matching logic is sequence matching .-->
<!--All logs, including from Microsoft-->
<!--<logger name="*" minlevel="Trace" writeTo="allfile" />-->
<!--Skip Microsoft logs and so log only own logs-->
<!-- With Microsoft The leading log will enter this route , Because this route has no writeTo attribute , All will be ignored -->
<!--
-->
<!-- And this route is set final, So when this route is matched . The route below this route will no longer be matched . The next route will not be matched until this route is not matched -->
<!--<logger name="Microsoft.*" minlevel="Trace" final="true" />-->
<!-- The top has filtered all Microsoft.* Log , So the log here will only print except Microsoft.* External log -->
<!--<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>
</nlog>
3.ASP.NET Core The program supports
public static void Main(string[] args)
{
// Read configuration file
NLogBuilder.ConfigureNLog("CfgFile/NLog.config");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseNLog();
4. Program log
Constructor injection
public class FirstController : Controller
{
private readonly ILogger<FirstController> _ILogger;
private readonly ILoggerFactory _ILoggerFactory;
public FirstController(ILogger<FirstController> logger, ILoggerFactory iLoggerFactory)
{
this._ILogger = logger;
_ILogger.LogInformation($"{this.GetType().FullName} Constructed ....LogInformation");
_ILogger.LogError($"{this.GetType().FullName} Constructed ....LogError");
_ILogger.LogDebug($"{this.GetType().FullName} Constructed ....LogDebug");
_ILogger.LogTrace($"{this.GetType().FullName} Constructed ....LogTrace");
_ILogger.LogCritical($"{this.GetType().FullName} Constructed ....LogCritical");
this._ILoggerFactory = iLoggerFactory;
ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
_ILogger2.LogInformation(" This is through Factory Got Logger Write a log ");
}
}
Two 、Nlog– Record database logs
1.Nuget Import assembly
Microsoft.Data.SqlClient
2. Modify the configuration file
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!--Optional, add some variables
Optional , Add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
See https://github.com/nlog/nlog/wiki/Configuration-file
Information about custom logging rules and output .
-->
<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.
Add your goal here
See https://github.com/nlog/NLog/wiki/Targets Look for possible targets .
See https://github.com/nlog/NLog/wiki/Layout-Renderers For possible layout renderers .
-->
<!--
The same is to write the file to the log , The content written is different ,
The difference is layout Property . There are differences in the number of logs written , The difference is reflected in the routing logic
-->
<!--<target xsi:type="File" name="allfile" fileName="Log\nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="ownFile-web" fileName="Log\nlog-my-${shortdate}.log"
layout="${longdate}|${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}" />
-->
<!-- Configuration is written to the database -->
<!-- Remarks:
The appsetting layouts require the NLog.Extended assembly.
The aspnet-* layouts require the NLog.Web assembly.
The Application value is determined by an AppName appSetting in Web.config.
The "NLogDb" connection string determines the database that NLog write to.
The create dbo.Log script in the comment below must be manually executed.
appsetting The layout needs NLog.Extended Assembly .
aspnet-* The layout needs NLog.Web Assembly .
The application value is determined by Web.config Medium AppName appSetting determine .
“NLogDb” The connection string determines NLog Write to the database .
The... In the following comments must be performed manually create dbo.Log Script .
Script for creating the dbo.Log table.
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] -->
<target name="AllDatabase" xsi:type="Database"
dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
connectionString="Data Source=DESKTOP-VUL99EF;Initial Catalog=CustomerDB;Persist Security Info=True;User ID=sa;Password=sa123;"
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>
</targets>
<rules>
<!-- add your logging rules here -->
<!-- Write to database -->
<logger name="*" minlevel="debug" writeTo="AllDatabase" />
<!-- Routing order will affect log printing . Route matching logic is sequence matching .-->
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<!-- With Microsoft The leading log will enter this route , Because this route has no writeTo attribute , All will be ignored -->
<!--
-->
<!-- And this route is set final, So when this route is matched . The route below this route will no longer be matched . The next route will not be matched until this route is not matched -->
<logger name="Microsoft.*" minlevel="Trace" final="true" />
<!-- The top has filtered all Microsoft.* Log , So the log here will only print except Microsoft.* External log -->
<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>
</nlog>
3. Execute database script
In fact, it is to generate a table for saving log data , Also correspond to this database , Generate the database link string configuration into the configuration file
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]
4. Read configuration file , Configuration and use Nlog
public static void Main(string[] args)
{
//NLogBuilder.ConfigureNLog("CfgFile/NLog.config");
NLogBuilder.ConfigureNLog("CfgFile/NLog.config");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
// Support records NLog journal
.ConfigureLogging(builder =>
{
builder.ClearProviders(); // Delete other registered ILogger Implement the program
builder.SetMinimumLevel(LogLevel.Debug);
})
.UseNLog();
3、 ... and 、NLog Expansion of configuration file
Configuration information expansion :
Logger Label pair , Control the output range and level
name attribute :
Specify which code snippets to output information , for example :“<logger name=“SomeNamespace.Component.*” …”, Only the output SomeNamespace.Component The information printed in the field .
minLevel attribute :
Specify the output level ,Logging The level is divided into the following levels “Trace<<Debug<<Info<<Warn<<Error<<Fatal ”, If we choose Info value , be Trace and Debug Level information will not be output .
writeTo attribute :
Specify that “Target Label pair ” To output information
Final attribute :
If this property is set to true, Is currently Logger Tag the type of message output , No longer be next Logger Label pair processing .
Target Label pair , Output format , Where to output
Name attribute :
target The name of the tag pair
Type attribute :
target The type of , such as target=”File”. also “Database”,“Mail”,“Network” Other types .
Silverlight Use file output , You need to set the item to Out of browser Pattern
fileName attribute :
if target The type is File, Then you can specify the output file name .
example :
fileName=”file.txt”,
fileName="${basedir}/App_Data/log.txt",
fileName="${basedir}/log.txt",
fileName =" s p e c i a l f o l d e r : M y D o c u m e n t s / l o g . {specialfolder:MyDocuments}/log. specialfolder:MyDocuments/log.{shortdate}.txt"
fileName="${logger}.txt"
fileName="${shortdate}.txt"
fileName="${windows-identity:domain=false}.txt
fileName=" s h o r t d a t e / {shortdate}/ shortdate/{windows-identity:domain=false}.txt"
If it is Silverlight The project may not be able to specify an output file to App_Data Under the table of contents .
Layout attribute :
Format output log information . example :
layout=" d a t e : f o r m a t = H H m m s s ∣ {date:format=HH\:mm\:ss}| date:format=HHmmss∣{level}| s t a c k t r a c e ∣ {stacktrace}| stacktrace∣{message}"
layout="[ d a t e : f o r m a t = y y y y − M M − d d H H m m s s ] [ {date:format=yyyy-MM-ddHH\:mm\:ss}][ date:format=yyyy−MM−ddHHmmss][{level}] ${message} ${exception}"
layout=" l o n g d a t e {longdate} longdate{callsite} ${level} ${message}"
address attribute :
Specify which network server the log information is output to , example :
<targetname=“n1” xsi:type="Network"address=“tcp://localhost:4001”/>
Four 、Log4Net Log
1.Nuget Import assembly
log4net
2. Add profile
Be careful : Profile information , It is recommended to set the property to always copy
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<!-- Define some output appenders -->
<appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
<file value="log\log.txt" />
<!-- Add log content -->
<appendToFile value="true" />
<!-- Prevent multithreading when unable to write Log, Officials say threads are not safe -->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!-- It can be for :Once|Size|Date|Composite-->
<!--Composite by Size and Date The combination of -->
<rollingStyle value="Composite" />
<!-- When backing up files , Suffix to the file name -->
<datePattern value="yyyyMMdd.TXT" />
<!-- Maximum number of logs , It's all the latest -->
<!--rollingStyle The node is Size when , There can only be value A journal -->
<!--rollingStyle The node is Composite when , Every day value A journal -->
<maxSizeRollBackups value="20" />
<!-- Available units :KB|MB|GB-->
<maximumFileSize value="3MB" />
<!-- Set as true, The current latest log file name is always file The name of the festival -->
<staticLogFileName value="true" />
<!-- Output level in INFO and ERROR Log 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>
3、ASP.NET Core take effect log4net
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
// Support Log4Net
.ConfigureLogging(builder =>
{
builder.AddLog4Net("CfgFile/log4net.Config");
});
4. Write the log
It can be done by Logger perhaps LogerFactory Inject to write log
public class FirstController : Controller
{
private readonly ILogger<FirstController> _ILogger;
private readonly ILoggerFactory _ILoggerFactory;
public FirstController(ILogger<FirstController> logger, ILoggerFactory iLoggerFactory)
{
this._ILogger = logger;
_ILogger.LogInformation($"{this.GetType().FullName} Constructed ....LogInformation");
_ILogger.LogError($"{this.GetType().FullName} Constructed ....LogError");
_ILogger.LogDebug($"{this.GetType().FullName} Constructed ....LogDebug");
_ILogger.LogTrace($"{this.GetType().FullName} Constructed ....LogTrace");
_ILogger.LogCritical($"{this.GetType().FullName} Constructed ....LogCritical");
this._ILoggerFactory = iLoggerFactory;
ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
_ILogger2.LogInformation(" This is through Factory Got Logger Write a log ");
}
}
版权声明
本文为[Caramel macchiato]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220608525405.html
边栏推荐
- Distributed task scheduling and computing framework: powerjob advanced features - container 03
- Alibaba cloud's deployment of rsshub stepping on the pit notes
- 假设成年人的体重和身高存在此种关系: 身高(厘米)-100=标准体重(千克) 如果一个人的体重与其标准体重的差值在正负5%之间,显示“体重正常”,其他则显示“体重超标”。编写程序,能处理用户输入的
- . net learning notes - about Net core (3) [reading configuration files, general parsing JSON files, reading static files]
- Introduction to IC Analog Layout - learning notes on layout Basics (3)
- 微信第三方网页授权
- 完成一个学生信息管理系统,系统练习面向对象、函数、字符串等知识。实现知识的综合应用。 使用类、函数、数据库等来实现
- 写一个方法sanjiao(a, b, c),判断三个参数是否能构成一个三角形,如果不能则抛出异常IllegalArgumentException,显示异常信息a,b,c”不能构成三角形”,如果可以
- 分布式任务调度与计算框架:PowerJob 快速开始(本地IDE版) 02
- 【Bug小记】antd表格高度自适应窗口高度
猜你喜欢

JS realizes clicking avatar to upload picture modification

Wechat third party web page authorization

JS实现点击头像上传图片修改

.NET学习笔记----关于.NET Core那些事(1)【.netcore的项目结构、五种向页面传值的方式、Log4Net和NLog的使用】

Clion and dynamic link library
![[bug notes] input: - WebKit autofill: the input box automatically fills in the background problem](/img/da/b737e837d5ff781f68608a6cd2c5da.png)
[bug notes] input: - WebKit autofill: the input box automatically fills in the background problem

short circuit

用大写的字段接受最终首字母却变小写

左移与右移

写一个方法sanjiao(a, b, c),判断三个参数是否能构成一个三角形,如果不能则抛出异常IllegalArgumentException,显示异常信息a,b,c”不能构成三角形”,如果可以
随机推荐
ASP.NET日常开发随手记------iis服务器支持下载apk
pyftpdlib中文乱码问题解决方案
Wechat third party web page authorization
浙大版《C语言程序设计(第3版)》题目集 练习7-4 找出不是两个数组共有的元素
MySQL完全卸载,mysql服务清理
Introduction to IC Analog Layout - learning notes on layout Basics (4)
实验室安全考试
ASP.NET日常开发随手记------发送邮件
Eight functions of random library
论文快速阅读的方法技巧
Nacos命名空间分组和DataID三者关系
ASP.NET日常开发随手记------webService服务端开发
. net learning notes - about Net core (3) [reading configuration files, general parsing JSON files, reading static files]
SQL server stored procedure development notes - piecemeal problems and operations on operation files
关于Log4Net和NLog使用的帮助文档
.NET日常想法随手记------比较两个json文件并获取标签相同但值却不同的数据
分布式任务调度与计算框架:PowerJob 高级特性-OpenAPI 04
模二除运算的上商原则
Introduction to IC Analog Layout - learning notes on layout Basics (I)
14行代码完成任意选择图片爬取