自定义日志模型

日志模型

LogDashboard提供了基础的日志模型,包含以下5个属性,代表着只有包含以下5个属性的日志才可以被LogDashboard解析
  • LongDate
  • Logger
  • Level
  • Message
  • Exception
除了以上5个预定义属性外,我们还可以自定义属性

创建NetCore项目

参考快速入门中的创建NetCore项目步骤
使用以下 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
throwExceptions="false"
6
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
7
8
<!-- optional, add some variables
9
https://github.com/nlog/NLog/wiki/Configuration-file#variables
10
-->
11
<variable name="myvar" value="myvalue"/>
12
13
<!--
14
See https://github.com/nlog/nlog/wiki/Configuration-file
15
for information on customizing logging rules and outputs.
16
-->
17
<targets>
18
19
<target xsi:type="file" name="File" fileName="${basedir}/logs/${shortdate}.log"
20
layout="${longdate}||${level}||${logger}||${message}||${exception:format=ToString:innerFormat=ToString:maxInnerExceptionLevel=10:separator=\r\n}||${var:application}||${var:requestMethod}||${machinename}||end" />
21
<!--
22
Write events to a file with the date in the filename.
23
24
-->
25
</targets>
26
27
<rules>
28
<logger name="*" minlevel="Error" writeTo="file" />
29
<!-- add your logging rules here -->
30
31
<!--
32
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
33
<logger name="*" minlevel="Debug" writeTo="f" />
34
-->
35
</rules>
36
</nlog>
37
Copied!

安装LogDashboard

准备工作已经结束,这时安装LogDashboard
1
Install-Package LogDashboard
Copied!

添加自定义日志模型

在项目中添加ApplicationLogModel类,并继承 LogModel 接口
1
public class ApplicationLogModel : LogModel
2
{
3
public string Application { get; set; }
4
5
public string RequestMethod { get; set; }
6
7
public string MachineName { get; set; }
8
}
Copied!
我们自定义了 ApplicationRequestMethodMachineName 属性
打开Startup.cs 文件
ConfigureServices 方法中配置服务
1
public void ConfigureServices(IServiceCollection services)
2
{
3
// 自定义变量
4
LogManager.Configuration.Variables["application"] = "CustomLogModel";
5
LogManager.Configuration.Variables["requestMethod"] = "Get";
6
services.AddLogDashboard(opt => { opt.CustomLogModel<ApplicationLogModel>(); });
7
}
Copied!
AddLogDashoard 时使用optionsCustomLogModel 方法注册自定义模型,并使用了nlog的方法进行自定义变量值,因为machineName 是nlog预定义的变量,所以不需要手动斌值。更多内容请参阅nlog文档
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
Last modified 2yr ago