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

我们需要添加依赖:

添加nlog.config文件

 <?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="Warn"
internalLogFile="logfiles/internal-nlog.txt"> <!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="${var:configDir}\nlog-all.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="${var:configDir}\nlog-own.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> <target name="database" xsi:type="Database"> <connectionString>${var:connectionString}</connectionString> <commandText>
insert into dbo.Log (
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}" />
<parameter name="@exception" layout="${exception:tostring}" />
</target>
</targets> <rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="database" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>

将nlog.config复制到输出目录

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

 using System;

 namespace Apps.Models
{
public class ApplicationLog
{
public int Id { get; set; }
public string Application { get; set; }
public DateTime Logged { get; set; }
public string Level { get; set; }
public string Message { get; set; }
public string Logger { get; set; }
public string Callsite { get; set; }
public string Exception { get; set; }
}
}
         protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ApplicationLog>(m =>
{
m.ToTable("Log");
m.HasKey(c => c.Id);
m.Property(c => c.Application).IsRequired().HasMaxLength();
m.Property(c => c.Level).IsRequired().HasMaxLength();
m.Property(c => c.Message).IsRequired();
m.Property(c => c.Logger).HasMaxLength();
});
}

在startup.cs文件中添加:

 using NLog.Extensions.Logging;
using NLog.Web; public Startup(IHostingEnvironment env)
{
env.ConfigureNLog("nlog.config");
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ loggerFactory.AddNLog(); app.AddNLogWeb();
LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value;
}

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"

然后就可以记录日志了

     public class HomeController :Controller {
private readonly ILogger _logger; public HomeController(ILoggerFactory loggerFactory) {
_logger = loggerFactory.CreateLogger<HomeController>();
}
public IActionResult Index() {
_logger.LogInformation("你访问了首页");
_logger.LogWarning("警告信息");
_logger.LogError("错误信息");
return View();
}
  }

ASP.NET Core使用NLog记录日志到Microsoft Sql Server的更多相关文章

  1. asp.net core 使用NLog记录日志到txt文件

    一.使用VisualStudioCode创建一个webapi项目(也可以是mvc等).一个类库(用于封装记录日志方法,当然如果使用依赖注入到控制台项目,就不需要此类库了). 二.在类库中添加NLog. ...

  2. ASP.NET Core使用NLog记录日志

    1.根目录新建nlog.config配置文件 <?xml version="1.0"?> <nlog xmlns="http://www.nlog-pr ...

  3. ASP .Net Core 在 CentOS8 ARM 下连接 SQL Server 2008 R2(Hypervisor)

    本文主要记录在 ARM 系统下无法连接SQL Server 2008 R2 的解决过程. 解决方案是使用 ODBC 的方式连接数据库,进行操作. 手上有公司的华为鲲鹏云计算 ARM 架构的 CentO ...

  4. asp.net core结合NLog搭建ELK实时日志分析平台

    0.整体架构 整体架构目录:ASP.NET Core分布式项目实战-目录 一.介绍ELK 1.说明(此篇ELK采用rpm的方式安装在服务器上)-牛刀小试 承接上一篇文章的内容准备部署ELK来展示asp ...

  5. [.Net Core] - 使用 NLog 记录日志到 Sql Server

    1. 使用 Nuget 安装 NLog. 2. 在 Sql Server 中创建 NLog 数据表. CREATE TABLE [dbo].[NLogInfo]( ,) NOT NULL, [Date ...

  6. Cenots7下安装运行.NET Core、MicroSoft SQL Server 2019 preview 的基础实践

    一:概要 适应人群:.Net初学者.想了解.Net Core在Linux系统中的运行环境搭建者.初次且想在linux上应用.Net Core开发应用程序者: 基础技能:了解.NET基础开发技能者.有一 ...

  7. asp.net编译中出现 数据库 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\test1.mdf' 已存在。请选择其他数据库名称。

    关于asp.net编译中出现数据库 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\test1.mdf ...

  8. Microsoft SQL Server Compact 4.0&&ADO.NET Entity Framework 4.1&&MVC3

    最近重新查看微软MvcMusicStore-v3.0的源代码,发现忽略了很多重要的东西,特别是数据访问那一部分. 首先Microsoft SQL Server Compact 4.0 详细的介绍和下载 ...

  9. 使用 Oracle GoldenGate 在 Microsoft SQL Server 和 Oracle Database 之间复制事务

    使用 Oracle GoldenGate 在 Microsoft SQL Server 和 Oracle Database 之间复制事务 作者:Nikolay Manchev 分步构建一个跨这些平台的 ...

随机推荐

  1. codeblock 生成和使用makefile

    下载cbp2make 文件名:cbp2make-stl-rev138.tar.gz 里面有个cbp文件用codeblock打开,编译,生成的bin目录下有个执行文件. 使用命令生成Makefile . ...

  2. Linux下Oracle开机启动

    参考:http://blog.csdn.net/huangyanlong/article/details/36942155 一.保证dbstart能用:vi $ORACLE_HOME/bin/dbst ...

  3. Docker镜像仓库Harbor搭建及配置

    一.harbor简介 Harbor是一个用于存储和分发Docker镜像的企业级Registry服务器,通过添加一些企业必需的功能特性,例如安全.标识和管理等,扩展了开源Docker Distribut ...

  4. 【HP-UNIX】修改HP-UNIX主机名称

    原文链接:https://blog.csdn.net/lantianbaiyunbj/article/details/53434537 HP-UX修改主机IP地址 方法一 1.set_parms ho ...

  5. C#通过COM组件调用IDL的pro程序

    如果在“COM_IDL_connectLib.COM_IDL_connect oComIDL = new COM_IDL_connectLib.COM_IDL_connect();”步骤提示“...8 ...

  6. 渐进反馈式搜索技术助力运维工程师——Linux命令高效检索

    日常生活工作中,我们通过搜索引擎查询相关资料时,经常遇到不知如何指定准确关键词的情况,仅仅根据指定大概范围的关键词时,搜索结果往往不能尽如人意. <信息导航>APP最新版本(Ver 1.1 ...

  7. cached_property的使用

    cached_property修饰过的函数,变成是对象的属性,该对象第一次引用该属性时,会调用函数,对象第二次引用该属性时就直接从词典中取了,这也说明引用属性是经过__getattritue__. c ...

  8. 魔力Python--if __name__ == '__main__' 的理解

    if __name__ == '__main__' 的理解 __name__ 是当前模块名,当模块被直接运行时模块名为 __main__ . 这句话的意思就是,当模块被直接运行时,以下代码块将被运行, ...

  9. HTML5 汉字转化为拼音,带读声,穷举多音字

    1,没别的,像这种没有规则的转化,我们首先需要一个字典文件,字典文件的完整度,决定了转化的成功率与精确度 2,笔者收集了较为完整的字典文件,已上传到博客园,欢迎补充  =>  https://b ...

  10. Docker技术应用场景(转载)

    场景一:节省项目环境部署时间 1.单项目打包 每次部署项目到测试.生产等环境,都要部署一大堆依赖的软件.工具,而且部署期间出现问题几率很大,不经意就花费了很长时间. Docker主要理念就是环境打包部 ...