简体   繁体   English

配置NLog的布局以显示所有事件上下文条目

[英]configuring NLog's layout to show all the event-context entries

im currently in the process of developing a webapi2 application, and in the stages of conducting my logs using NLog. 我目前正在开发webapi2应用程序,并在使用NLog进行日志的阶段。

in my application i log in a key-value manner using the LogEventInfo.Properties dictionary in this way: 在我的应用程序中,我以这种方式使用LogEventInfo.Properties字典以键值方式登录:

thisController.LogParams.Add("ControllerName",controllerName);
thisController.LogParams.Add("ActionName", actionName);
thisController.LogParams.Add("TotalTime", actionWatch.ElapsedMilliseconds);
LogEventInfo logEvent = new LogEventInfo() 
       { 
           Message = string.IsNullOrEmpty(thisController.LogMessage)? "Finished Successfuly":thisController.LogMessage,
           Level = LogLevel.Info,
           TimeStamp = DateTime.Now
       };
logEvent.Properties.Merge(thisController.LogParams);
logger.Log(logEvent);

everything works fine, however I cant seem to find the way to render the layout so it prints all the key-value entries that are in the LogEventInfo.Properties dictionary. 一切正常,但我似乎无法找到渲染布局的方法,因此它打印LogEventInfo.Properties字典中的所有键值条目。

lets assume my target is a file, then i have to explicitly mention the key name, is there a way to render it to show all the content of the dictionary ? 假设我的目标是一个文件,那么我必须明确提到密钥名称,有没有办法渲染它来显示字典的所有内容? this is how i do it today, where i can log only the entries i know of: 这是我今天如何做到这一点,我只能记录我所知道的条目:

<target name="f1" 
  xsi:type="File" 
  fileName="${basedir}\logs\log.txt" 
  maxArchiveFiles="60" 
  archiveNumbering="Date" 
  archiveDateFormat="yyyyMMdd" 
  archiveEvery="Day" 
  layout="${longdate} : ${callsite:className=true:methodName=true} : ${event-context:item=ControllerName} : ${event-context:item=ActionName} : ${event-context:item=TotalTime} : ${message}" />

There's no built-in support that can render all properties at once. 没有可以一次呈现所有属性的内置支持。 If you look at the code in event-context layout renderer then it's only adding single value of property based on item ie property name. 如果您查看事件上下文布局渲染器中的代码,那么它只会根据项目属性名称添加单个属性值。

You can create your custom Layout renderer that can print all the properties from LogEventInfo. 您可以创建可以从LogEventInfo打印所有属性的自定义布局渲染器。 Instead of fetching value of property based on item just add them all to string builder which will get printed to target. 而不是基于项目获取属性值只需将它们全部添加到字符串构建器,它将打印到目标。

using System;
using System.Globalization;
using System.Text;
using NLog.Config;
namespace CustomLayoutRenderer
{
    /// <summary>
    /// Log event context data.
    /// </summary>
    [LayoutRenderer("event-context-all")]
    public class EventContextLayoutRenderer : LayoutRenderer
    {
        /// <summary>
        /// Renders the specified log event context item and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            foreach (var item in logEvent.Properties)
            {
                // item is a keyvalue pair object you can custom format the key value as needed.
                builder.Append(Convert.ToString(item.Value, CultureInfo.InvariantCulture));
            }

        }
    }
}

You can register this custom layout renderer using <extension> tag in Nlog configuration file. 您可以使用Nlog配置文件中的<extension>标记注册此自定义布局渲染器。

<nlog> 
  <extensions> 
    <!-- Add the assembly name which contains the custom layout renderer -->
    <add assembly="MyAssembly"/> 
  </extensions> 
  <targets> 
    <target name="f1" type="file"  layout="${longdate} ${event-context-all}" 
            fileName="${basedir}/logs/logfile.log" />
  </targets> 
</nlog>

This shall print the all properties values only without requiring the item name. 这将values only打印所有属性values only而无需项目名称。

There is a built-in layout renderer in NLog which serves that purpose - ${all-event-properties}. NLog中有一个内置的布局渲染器,用于实现这一目的 - $ {all-event-properties}。 By default it emits all event context properties in key-value style, comma separated. 默认情况下,它以键值样式发出所有事件上下文属性,以逗号分隔。

Checkout the docs for more details https://github.com/NLog/NLog/wiki/All-Event-Properties-Layout-Renderer 查看文档以获取更多详细信息https://github.com/NLog/NLog/wiki/All-Event-Properties-Layout-Renderer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM