Links

自定义日志模型

日志模型

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

创建NetCore项目

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

安装LogDashboard

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

添加自定义日志模型

在项目中添加ApplicationLogModel类,并继承 LogModel 接口
public class ApplicationLogModel : LogModel
{
public string Application { get; set; }
public string RequestMethod { get; set; }
public string MachineName { get; set; }
}
我们自定义了 ApplicationRequestMethodMachineName 属性
打开Startup.cs 文件
ConfigureServices 方法中配置服务
public void ConfigureServices(IServiceCollection services)
{
// 自定义变量
LogManager.Configuration.Variables["application"] = "CustomLogModel";
LogManager.Configuration.Variables["requestMethod"] = "Get";
services.AddLogDashboard(opt => { opt.CustomLogModel<ApplicationLogModel>(); });
}
AddLogDashoard 时使用optionsCustomLogModel 方法注册自定义模型,并使用了nlog的方法进行自定义变量值,因为machineName 是nlog预定义的变量,所以不需要手动斌值。更多内容请参阅nlog文档
Configure 方法配置中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseLogDashboard();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
运行项目导航到 /logdashboard
enjoy