在之前的文章中介绍了如何在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. linux上安装mysql5.6

    CentOS-6.6+MySQL-5.6 部署环境操作系统:CentOS-6.6-x86_64-bin-DVD1.isoMySQL 版本:mysql-5.6.26.tar.gz操作用户:root系统 ...

  2. k8s 命令补全

    安装:apt-get install bash-completion source <(kubectl completion bash) echo "source <(kubec ...

  3. react基础学习 二——生命周期

    生命周期mount: mounting装载创建 update更新 unmounting卸载 错误捕获 注意点:生命周期函数的 作用,什么之后用 只有类式组件有生命周期,函数式组件没有生命周期 moun ...

  4. 用python进行有进度条的圆周率计算

    一.安装tqdm函数库 tqdm是一个强大的终端进度条工具,我利用pip获取tqdm函数库. 1.打开运行,输入“cmd” 2.2:输入pip install   你要安装的库(如 pip insta ...

  5. python爬取免费优质IP归属地查询接口

    python爬取免费优质IP归属地查询接口 具体不表,我今天要做的工作就是: 需要将数据库中大量ip查询出起归属地 刚开始感觉好简单啊,毕竟只需要从百度找个免费接口然后来个python脚本跑一晚上就o ...

  6. H5使用codovar插件实现支付宝支付(支付宝APP支付模式,前端)

    H5打包的app实现支付及支付宝支付,本章主要详解支付宝支付,微信支付请查看另一篇“H5使用codovar插件实现微信支付(微信APP支付模式,前端)” ps:本文只试用H5开发的,支付宝 APP支付 ...

  7. tensorflow 如何读取npy文件里的参数

    import numpy as npc = np.load( "vgg16.npy" )   #npy的文件名x = c.item()     #此时,x的type是一个字典nam ...

  8. Mongodb到mysql数据库的数据迁移(Java,Windows)

    运行环境为windows 测试过260万的数据表,迁移大概要10分钟左右,当然肯定和网络,字段大小什么的有关系. 遇到的坑和注意点都用紫色标记了(对,就是我大乃团的高冷紫--Nogizaka 46) ...

  9. 团队作业5——《Spring_Four》项目需求改进与系统设计

    团队项目需求分析改进: 任务1: a.分析<基于Jsoup的大学生考试信息展示系统项目需求规格说明书>初稿的不足,特别是文档需求描述建模不完整的内容. 通过软件工程更深入的学习发现我们的需 ...

  10. 吴裕雄 python 机器学习——逻辑回归

    import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot ...