ASP.NET Core使用NLog记录日志到Microsoft Sql Server
在之前的文章中介绍了如何在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的更多相关文章
- asp.net core 使用NLog记录日志到txt文件
一.使用VisualStudioCode创建一个webapi项目(也可以是mvc等).一个类库(用于封装记录日志方法,当然如果使用依赖注入到控制台项目,就不需要此类库了). 二.在类库中添加NLog. ...
- ASP.NET Core使用NLog记录日志
1.根目录新建nlog.config配置文件 <?xml version="1.0"?> <nlog xmlns="http://www.nlog-pr ...
- ASP .Net Core 在 CentOS8 ARM 下连接 SQL Server 2008 R2(Hypervisor)
本文主要记录在 ARM 系统下无法连接SQL Server 2008 R2 的解决过程. 解决方案是使用 ODBC 的方式连接数据库,进行操作. 手上有公司的华为鲲鹏云计算 ARM 架构的 CentO ...
- asp.net core结合NLog搭建ELK实时日志分析平台
0.整体架构 整体架构目录:ASP.NET Core分布式项目实战-目录 一.介绍ELK 1.说明(此篇ELK采用rpm的方式安装在服务器上)-牛刀小试 承接上一篇文章的内容准备部署ELK来展示asp ...
- [.Net Core] - 使用 NLog 记录日志到 Sql Server
1. 使用 Nuget 安装 NLog. 2. 在 Sql Server 中创建 NLog 数据表. CREATE TABLE [dbo].[NLogInfo]( ,) NOT NULL, [Date ...
- Cenots7下安装运行.NET Core、MicroSoft SQL Server 2019 preview 的基础实践
一:概要 适应人群:.Net初学者.想了解.Net Core在Linux系统中的运行环境搭建者.初次且想在linux上应用.Net Core开发应用程序者: 基础技能:了解.NET基础开发技能者.有一 ...
- 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 ...
- Microsoft SQL Server Compact 4.0&&ADO.NET Entity Framework 4.1&&MVC3
最近重新查看微软MvcMusicStore-v3.0的源代码,发现忽略了很多重要的东西,特别是数据访问那一部分. 首先Microsoft SQL Server Compact 4.0 详细的介绍和下载 ...
- 使用 Oracle GoldenGate 在 Microsoft SQL Server 和 Oracle Database 之间复制事务
使用 Oracle GoldenGate 在 Microsoft SQL Server 和 Oracle Database 之间复制事务 作者:Nikolay Manchev 分步构建一个跨这些平台的 ...
随机推荐
- mint linux 18.3 遇到“已安装的 post-installation 脚本 返回了错误号 127 ”问题的解决
From https://blog.csdn.net/ropai/article/details/27171687 ubuntu 14.04遇到“已安装的 post-installation 脚本 返 ...
- pyinstaller 打包生成exe之后运行提示‘no module name 'xxx'’错误
python 3.7 pyinstaller 3.4 具体情况: pycharm中点击运行可成功执行,生成正确结果,没有报错. 双击run.py(程序运行的主文件),运行,可生成正确结果,没有报错. ...
- PHP SoapClient 调用与鉴权,以及对Java和C# 的webservice的兼容处理
SoapClient使用注意事项: 第一要加上 cache_wsdl参数,以防服务器调用的是缓存的wsdl文件 然后是参数传递,如果是使用PHP自己写的WebService,参数传递按正常方式即可 1 ...
- css样式基础详解
一.字体属性:(font) 1.大小 {font-size: x-large;}(特大) xx-small;(极小) 一般中文用不到,只要用数值就可以,单位:PX.PD 2.样式 {font-styl ...
- ThinkPHP实现支付宝接口功能 代码实例
我们这里用的是即时到帐的接口,具体实现的步骤如下: [title]一.下载支付宝接口包[/title]下载地址:https://doc.open.alipay.com/doc2/detail?tree ...
- 【396】python 递归练习题(COMP9021)
Merging two strings into a third one Say that two strings s1 and s2 can be merged into a third strin ...
- 新年Flag,零基础程序媛编程学习计划(持续更新ing)~~
新的一年立下了转行做程序媛的Flag,我是文科妹子,专业是做市场传销…哦不,是市场营销,算是零基础转行,目标是半年内完成自学进入公司工作,目前打算从事的方向短期目标以入行为主,以前端(可以发挥自身审美 ...
- 多元高斯分布(The Multivariate normal distribution)
在数据建模时,经常会用到多元高斯分布模型,下面就这个模型的公式并结合它的几何意义,来做一个直观上的讲解. 1, 标准高斯函数 高斯函数标准型: $f(x) = \frac{1}{\sqrt{2π}}e ...
- GhostScript应用一例:使用GhostScript强行修改加密PDF
GhostScript官方网站为:http://www.ghostscript.com/ 作为一个英文开源软件,发现国内用的人很少.尤其是在Windows环境下,Acrobat/Adobe/Foxit ...
- 安装oracle [INS-32025] 所选安装与指定 Oracle 主目录中已安装的软件冲突” 的问题
删除C:\Program Files (x86)\Oracle\Inventory\下的Oracle文件夹即可解决问题