ASP.NET Core使用NLog记录日志到Microsoft Sql Server

   2023-02-09 学习力0
核心提示:在之前的文章中介绍了如何在ASP.NET Core使用NLog,本文为您介绍在ASP.NET Core使用NLog记录到Microsoft Sql ServerNLog.Web.AspNetCoreSystem.Data.SqlClient添加nlog.config文件 1 ?xml version="1.0" encoding="utf-8" ? 2 nlog xmlns="http://www.nlog-pro

在之前的文章中介绍了如何在ASP.NET Core使用NLog,本文为您介绍在ASP.NET Core使用NLog记录到Microsoft Sql Server

添加nlog.config文件

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       autoReload="true"
 5       internalLogLevel="Warn"
 6       internalLogFile="logfiles/internal-nlog.txt">
 7 
 8   <!-- define various log targets -->
 9   <targets>
10     <!-- write logs to file -->
11     <target xsi:type="File" name="allfile" fileName="${var:configDir}\nlog-all.log"
12             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
13 
14 
15     <target xsi:type="File" name="ownFile-web" fileName="${var:configDir}\nlog-own.log"
16             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />
17 
18     <target xsi:type="Null" name="blackhole" />
19 
20     <target name="database" xsi:type="Database">
21 
22       <connectionString>${var:connectionString}</connectionString>
23 
24  
25       <commandText>
26         insert into dbo.Log (
27         Application, Logged, Level, Message,
28         Logger, Callsite, Exception
29         ) values (
30         @Application, @Logged, @Level, @Message,
31         @Logger, @Callsite, @Exception
32         );
33       </commandText>
34 
35       <parameter name="@application" layout="AspNetCoreNlog" />
36       <parameter name="@logged" layout="${date}" />
37       <parameter name="@level" layout="${level}" />
38       <parameter name="@message" layout="${message}" />
39 
40       <parameter name="@logger" layout="${logger}" />
41       <parameter name="@callSite" layout="${callsite}" />
42       <parameter name="@exception" layout="${exception:tostring}" />
43     </target>
44   </targets>
45 
46   <rules>
47     <!--All logs, including from Microsoft-->
48     <logger name="*" minlevel="Trace" writeTo="allfile" />
49     
50     <!--Skip Microsoft logs and so log only own logs-->
51     <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
52     <logger name="*" minlevel="Trace" writeTo="database" />
53     <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
54   </rules>
55 </nlog>

将nlog.config复制到输出目录

ASP.NET Core使用NLog记录日志到Microsoft Sql Server

 

设置数据库(我使用的是ef code first方式创建数据表)

 1 using System;
 2 
 3 namespace Apps.Models
 4 {
 5     public class ApplicationLog
 6     {
 7         public int Id { get; set; }
 8         public string Application { get; set; }
 9         public DateTime Logged { get; set; }
10         public string Level { get; set; }
11         public string Message { get; set; }
12         public string Logger { get; set; }
13         public string Callsite { get; set; }
14         public string Exception { get; set; }
15     }
16 }
 1         protected override void OnModelCreating(ModelBuilder builder)
 2         {
 3             builder.Entity<ApplicationLog>(m =>
 4             {
 5                 m.ToTable("Log");
 6                 m.HasKey(c => c.Id);
 7                 m.Property(c => c.Application).IsRequired().HasMaxLength(50);
 8                 m.Property(c => c.Level).IsRequired().HasMaxLength(50);
 9                 m.Property(c => c.Message).IsRequired();
10                 m.Property(c => c.Logger).HasMaxLength(250);
11             });
12         }

在startup.cs文件中添加:

 1 using NLog.Extensions.Logging;
 2 using NLog.Web;
 3 
 4 public Startup(IHostingEnvironment env)
 5 {
 6     env.ConfigureNLog("nlog.config");
 7 }
 8 
 9 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
10 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
11 {
12 
13 
14     loggerFactory.AddNLog();
15 
16     app.AddNLogWeb();
17     LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
18     LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value;
19 }

appsettings.json

  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=logdb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  },
  "LogFilesDir": "c:\\temp\\nlog\\logfiles" 

然后就可以记录日志了

 1     public class HomeController :Controller {
 2         private readonly ILogger _logger;
 3 
 4         public HomeController(ILoggerFactory loggerFactory) {
 5             _logger = loggerFactory.CreateLogger<HomeController>();
 6         }
 7         public IActionResult Index() {
 8             _logger.LogInformation("你访问了首页");
 9             _logger.LogWarning("警告信息");
10             _logger.LogError("错误信息");
11             return View();
12         }
13   }

ASP.NET Core使用NLog记录日志到Microsoft Sql Server

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 使用WebClient自动填写并提交ASP.NET页面表单的源代码
    使用WebClient自动填写并提交ASP.NET页面表单的
    转自:http://www.cnblogs.com/anjou/archive/2007/03/07/667253.html 在.NET中通过程序填写和提交表单还是比较简单。比如,要提交一个如下图所示的登录表单:           填写和提交以上表单的代码如下:       // 要提交表单的URI字符串
    02-09
  • asp.net mvc多条件+分页查询解决方案
    


            
asp.net mvc多条件+分页查询解决方案
    asp.net mvc多条件+分页查询解决方案
    http://www.cnblogs.com/nickppa/p/3232535.html开发环境vs2010css:bootstrapjs:jquery    bootstrap paginator原先只是想做个mvc的分页,但是一般的数据展现都需要检索条件,而且是多个条件,所以就变成了MVC多条件+分页查询因为美工不是很好,所以用的是
    02-09
  • ASP.NET操作Cookies的问题(Bug or Not)
    以下存和取都是在不同的页面中,如果是在同一个页面也没必要用cookies了。 Test1: 给Cookies赋值: const string AAA="aaa"; Response.Cookies[AAA].Value = "111;222;333"; 取值: string value = Request.Cookies[AAA].Value; // value为111 Test2: 给Cooki
    02-09
  • Asp.Net Core 自定义验证属性
      很多时候,在模型上的验证需要自己定义一些特定于我们需求的验证属性。所以这一篇我们就来介绍一下怎么自定义验证属性。  我们来实现一个验证邮箱域名的自定义验证属性,当然,最重要的是需要定义一个继承自ValidationAttribute的类,然后在实现其IsVal
    02-09
  • Asp.Net 之 枚举类型的下拉列表绑定
    有这样一个学科枚举类型:/// 学科 /// /summary public enum Subject {None = 0,[Description("语文")]Chinese = 1,[Description("数学")]Mathematics = 2,[Description("英语")]English = 3,[Description("政治")]Politics = 4,[Description("物理&qu
    02-09
  • [ASP.NET笔记] 1.Web基础知识
         1:http协议:     2:web服务器:     3:静态网页的概念     4:动态网页的概念       http协议:http(hypertext transfer protocol) 即超文本传输协议,这个协议是在internet上进行信息传送的协议任何网页之间要相互沟通,必须要尊循
    02-09
  • ASP.NET邮件发送 .net 发送邮件
      今天做了个ASP.NET做发送邮件功能,发现QQ邮箱好奇怪,当你用QQ邮箱做服务器的时候什么邮件都发送不出去(QQ邮箱除外)。而且爆出这样的错误:"邮箱不可用。 服务器响应为: Error: content rejected.http://mail.qq.com/zh_CN/help/content/rejectedmail.ht
    02-09
  • 由ASP.NET Core根据路径下载文件异常引发的探究
    前言    最近在开发新的项目,使用的是ASP.NET Core6.0版本的框架。由于项目中存在文件下载功能,没有使用类似MinIO或OSS之类的分布式文件系统,而是下载本地文件,也就是根据本地文件路径进行下载。这其中遇到了一个问题,是关于如何提供文件路径的,通
    02-09
  • ASP.NET的运行原理与运行机制 ASP.NET的开发模式包括
    ASP.NET的运行原理与运行机制 ASP.NET的开发模
    在Asp.net4和4.5中,新增了WebPages Framework,编写页面代码使用了新的Razor语法,代码更加的简洁和符合Web标准,编写方式更接近于PHP和以前的Asp,和使用WebForms这种模仿Windows Form编程方式有了很大不同,不再有大量控件和控件生成的大量不够灵活的代码
    02-09
  • ASP.NET 后台接收前台POST过来的json数据方法
     ASP.NET前后台交互之JSON数据 https://www.cnblogs.com/ensleep/p/3319756.html
    02-09
点击排行