Net6+NLog 写入数据库 Sql Server为例

这个百度一大片,到处不行,国外网站找也是有问题,官网文档也是有点操蛋。搞到现在ok了 直接上代码。

1
2
3
4
5
6
7
8
//Program.cs 配置<br> #region 日志 
       LogManager.LoadConfiguration(ParameterConfig.Nlog).GetCurrentClassLogger();
       builder.Logging.AddNLog(ParameterConfig.Nlog);//你nlog文件名称
       LogManager.Configuration.Variables["connectionString"] = builder.Services.AddNLogConnection(builder.Configuration);//这里是你要数据库的链接
       //.Variables["connectionString"] = services.AddNLogConnection(builder.Configuration);
       Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);  //避免日志中的中文输出乱码
 
 #endregion

  数据库表

复制代码
CREATE TABLE [dbo].[AICFlowStatistics_T_NLog](
    [Id] [BIGINT] 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
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
复制代码

 

Config配置文件

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?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"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">
 
    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>
 
    <!-- the targets to write to -->
    <targets>
        <!--database-->
        <target name= "allDatabase" xsi:type="Database"
            dbProvider="System.Data.SqlClient.SqlConnection, System.Data"
            connectionString="${var:connectionString}">
            <commandText>
                INSERT INTO dbo.AICFlowStatistics_T_NLog ([Application], [Logged], [Level], [Message], [Logger], [CallSite],[Exception]) VALUES (@application, @logged, @level, @message,@logger, @callSite, @exception);
            </commandText>
            <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>
        <!-- File Target for all log messages with basic details -->
        <target xsi:type="File" name="allfile" fileName="NLog\nlog-all-${shortdate}.log"
                layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
 
        <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="NLog\nlog-my-${shortdate}.log"
                layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
        <target xsi:type="Null" name="blackhole"/>
    </targets>
 
    <!-- rules to map from logger name to target -->
    <rules>
        <logger name="*" minlevel="Warning" writeTo="allDatabase" />
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />
        <!--Output hosting lifetime messages to console target for faster startup detection -->
        <!--<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole,ownFile-web" final="true" />-->
        <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
        <logger name="Microsoft.*" maxlevel="Trace" final="true" />
        <!--<logger name="System.Net.Http.*" maxlevel="Info" final="true" />-->
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    </rules>
</nlog><br><br><br>

 下图为依赖的包

 

 

 最后启动 要利用注入 写入

 

 

 

成功写入

 

 

 

1
2
3
4
5
6
7
8
9
10
11
下面控制记录那种级别的日志, Warning 只会记录警告及以上的日志,如果为Trace,就是N多日志,记得改下<br><br><rules>
        <logger name="*" minlevel="Warning" writeTo="allDatabase" />
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />
        <!--Output hosting lifetime messages to console target for faster startup detection -->
        <!--<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole,ownFile-web" final="true" />-->
        <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
        <logger name="Microsoft.*" maxlevel="Trace" final="true" />
        <!--<logger name="System.Net.Http.*" maxlevel="Info" final="true" />-->
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    </rules>

  

 

posted @   孤海飞雁  阅读(284)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示