使用数据库源

创建NotCore项目

确保机器上安装上NetCore SDK ,同快速入门一样,我们需要一个NetCore Empty项目 。打开PowerShell运行以下命令
1
dotnet new empty
Copied!
打开appsettings.json添加连接字符串配置
1
"ConnectionStrings": {
2
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=log;Trusted_Connection=True;MultipleActiveResultSets=true"
3
}
Copied!

安装Nlog日志组件

使用VSCode或VisualStudio打开项目,这时我们还需要做一些其他的准备工作。日志组件选用Nlog
1
Install-Package NLog.Web.AspNetCore
Copied!
打开Program.csCreateWebHostBuilder方法中添加Nlog中间件,复制以下代码覆盖CreateWebHostBuilder方法
1
public static IWebHost CreateWebHostBuilder(string[] args) =>
2
WebHost.CreateDefaultBuilder(args)
3
.UseStartup<Startup>()
4
.ConfigureLogging(logging =>
5
{
6
logging.ClearProviders();
7
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
8
})
9
.UseNLog()
10
.Build();
Copied!
添加一个Nlog.config到项目中,并右键文件设置为复制到输出目录(始终复制),以下是Nlog.config的全部内容 注释中的代码是创建数据库和表的SQL,请在DBMS中执行
1
<?xml version="1.0" encoding="utf-8" ?>
2
3
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
4
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
autoReload="true">
6
7
<targets>
8
<target name="database" xsi:type="Database">
9
<connectionString>${var:ConnectionString}</connectionString>
10
<!--
11
USE [master]
12
GO
13
/****** Object: Database [log] Script Date: 2019/1/3 15:06:59 ******/
14
CREATE DATABASE [log]
15
CONTAINMENT = NONE
16
ON PRIMARY
17
( NAME = N'log', FILENAME = N'C:\Users\admin\log.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
18
LOG ON
19
( NAME = N'log_log', FILENAME = N'C:\Users\admin\log_log.ldf' , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
20
GO
21
ALTER DATABASE [log] SET COMPATIBILITY_LEVEL = 130
22
GO
23
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
24
begin
25
EXEC [log].[dbo].[sp_fulltext_database] @action = 'enable'
26
end
27
GO
28
ALTER DATABASE [log] SET ANSI_NULL_DEFAULT OFF
29
GO
30
ALTER DATABASE [log] SET ANSI_NULLS OFF
31
GO
32
ALTER DATABASE [log] SET ANSI_PADDING OFF
33
GO
34
ALTER DATABASE [log] SET ANSI_WARNINGS OFF
35
GO
36
ALTER DATABASE [log] SET ARITHABORT OFF
37
GO
38
ALTER DATABASE [log] SET AUTO_CLOSE OFF
39
GO
40
ALTER DATABASE [log] SET AUTO_SHRINK OFF
41
GO
42
ALTER DATABASE [log] SET AUTO_UPDATE_STATISTICS ON
43
GO
44
ALTER DATABASE [log] SET CURSOR_CLOSE_ON_COMMIT OFF
45
GO
46
ALTER DATABASE [log] SET CURSOR_DEFAULT GLOBAL
47
GO
48
ALTER DATABASE [log] SET CONCAT_NULL_YIELDS_NULL OFF
49
GO
50
ALTER DATABASE [log] SET NUMERIC_ROUNDABORT OFF
51
GO
52
ALTER DATABASE [log] SET QUOTED_IDENTIFIER OFF
53
GO
54
ALTER DATABASE [log] SET RECURSIVE_TRIGGERS OFF
55
GO
56
ALTER DATABASE [log] SET DISABLE_BROKER
57
GO
58
ALTER DATABASE [log] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
59
GO
60
ALTER DATABASE [log] SET DATE_CORRELATION_OPTIMIZATION OFF
61
GO
62
ALTER DATABASE [log] SET TRUSTWORTHY OFF
63
GO
64
ALTER DATABASE [log] SET ALLOW_SNAPSHOT_ISOLATION OFF
65
GO
66
ALTER DATABASE [log] SET PARAMETERIZATION SIMPLE
67
GO
68
ALTER DATABASE [log] SET READ_COMMITTED_SNAPSHOT OFF
69
GO
70
ALTER DATABASE [log] SET HONOR_BROKER_PRIORITY OFF
71
GO
72
ALTER DATABASE [log] SET RECOVERY SIMPLE
73
GO
74
ALTER DATABASE [log] SET MULTI_USER
75
GO
76
ALTER DATABASE [log] SET PAGE_VERIFY CHECKSUM
77
GO
78
ALTER DATABASE [log] SET DB_CHAINING OFF
79
GO
80
ALTER DATABASE [log] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
81
GO
82
ALTER DATABASE [log] SET TARGET_RECOVERY_TIME = 60 SECONDS
83
GO
84
ALTER DATABASE [log] SET DELAYED_DURABILITY = DISABLED
85
GO
86
ALTER DATABASE [log] SET QUERY_STORE = OFF
87
GO
88
USE [log]
89
GO
90
ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
91
GO
92
ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
93
GO
94
ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
95
GO
96
ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
97
GO
98
USE [log]
99
GO
100
/****** Object: Table [dbo].[Log] Script Date: 2019/1/3 15:06:59 ******/
101
SET ANSI_NULLS ON
102
GO
103
SET QUOTED_IDENTIFIER ON
104
GO
105
CREATE TABLE [dbo].[Log](
106
[Id] [int] IDENTITY(1,1) NOT NULL,
107
[MachineName] [nvarchar](50) NOT NULL,
108
[LongDate] [datetime2] NOT NULL,
109
[Level] [nvarchar](50) NOT NULL,
110
[Message] [nvarchar](max) NOT NULL,
111
[Logger] [nvarchar](250) NULL,
112
[Callsite] [nvarchar](max) NULL,
113
[Exception] [nvarchar](max) NULL,
114
CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED
115
(
116
[Id] ASC
117
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
118
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
119
GO
120
USE [master]
121
GO
122
ALTER DATABASE [log] SET READ_WRITE
123
GO
124
125
-->
126
127
<commandText>
128
insert into dbo.Log (
129
MachineName, LongDate, Level, Message,
130
Logger, Callsite, Exception
131
) values (
132
@MachineName, @LongDate, @Level, @Message,
133
@Logger, @Callsite, @Exception
134
);
135
</commandText>
136
137
<parameter name="@MachineName" layout="${machinename}" />
138
<parameter name="@LongDate" layout="${longDate}" />
139
<parameter name="@Level" layout="${level}" />
140
<parameter name="@Message" layout="${message}" />
141
<parameter name="@Logger" layout="${logger}" />
142
<parameter name="@Callsite" layout="${callsite}" />
143
<parameter name="@Exception" layout="${exception:tostring}" />
144
</target>
145
</targets>
146
147
<rules>
148
<logger name="*" minlevel="Info" writeTo="database" />
149
</rules>
150
151
</nlog>
Copied!

安装LogDashboard

准备工作已经结束,这时安装LogDashboard
1
Install-Package LogDashboard
Copied!
打开Startup.cs我们要做两件事
  1. 1.
    ConfigureServices方法中配置服务
1
public void ConfigureServices(IServiceCollection services)
2
{
3
// 数据库连接字符串
4
var connectionString = Configuration.GetConnectionString("DefaultConnection");
5
LogManager.Configuration.Variables["ConnectionString"] = connectionString;
6
services.AddLogDashboard(opt =>
7
{
8
opt.UseDataBase(connectionString);
9
});
10
}
Copied!
关于更多的配置请参阅 LogDashboard配置
  1. 1.
    Configure方法中配置中间件
1
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
2
{
3
if (env.IsDevelopment())
4
{
5
app.UseDeveloperExceptionPage();
6
}
7
8
app.UseLogDashboard();
9
10
app.Run(async (context) =>
11
{
12
await context.Response.WriteAsync("Hello World!");
13
});
14
}
Copied!
大功告成,这时运行项目,在浏览器中导航到 /logdashboard
enjoy