gpt4 book ai didi

c# - NLog 自定义 LayoutRenderer - json : can't get working

转载 作者:太空狗 更新时间:2023-10-29 21:57:47 25 4
gpt4 key购买 nike

我是 NLog 的新手,大多数情况下它的设置非常简单。

我遇到的问题是设置自定义 LayoutRenderer

JsonLayoutRenderer.cs(命名空间:NBT.Logging;同一解决方案中的独立项目)

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Newtonsoft.Json.Linq;
using NLog;
using NLog.LayoutRenderers;

namespace NBT.Logging
{
[LayoutRenderer("json")]
public class JsonLayoutRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{

dynamic logEntry = new JObject();
logEntry.TimeStamp = logEvent.TimeStamp.ToString("yyyy-MM-ddTHH:mm:ss.mmmzzz", CultureInfo.InvariantCulture);
logEntry.TimeStampUTC = logEvent.TimeStamp.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.mmmZ", CultureInfo.InvariantCulture);
logEntry.Level = logEvent.Level.ToString();
logEntry.LoggerName = logEvent.LoggerName;
logEntry.Message = logEvent.FormattedMessage;

foreach(var prop in logEvent.Properties)
{
logEntry[prop.Key.ToString()] = prop.Value.ToString();
}
var json = logEntry.ToString(Formatting.None);
builder.Append(json);

}
}
}

代码取自 https://gist.github.com/caevyn/9594522

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" throwExceptions="true">

<extensions>
<add assembly="NLog.Targets.Redis"/>
<add assembly="NBT.Logging" />
</extensions>

<targets async="true">
<target xsi:type="Redis" name="redis" host="127.0.0.1" key="logstash" dataType="channel" layout="${longdate}|${level:uppercase=true}|${logger}|${message}|j|${json}"/>
</targets>

<rules>
<logger name="*" minlevel="Info" writeTo="redis" />
</rules>
</nlog>

因此到 redis 的日志记录显示所有正常布局项但不显示 ${json} 位

“2014-05-17 12:36:58.7480|INFO|ExampleController|Index loaded|j|”

可能遗漏了一些简单的东西。

更新(向 Global.asax.cs 添加了寄存器 layoutRenderer)

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();

// Register custom Model Binders
ModelBinderConfig.RegisterModelBinders();

ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("json", typeof(JsonLayoutRenderer));

}

最佳答案

也可以将程序集添加到包含自定义布局渲染器的 NLog.config:

<extensions>
<add assembly="MyNLogExtensions"/>
</extensions>

参见 this other post .

关于c# - NLog 自定义 LayoutRenderer - json : can't get working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23710935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com