简体   繁体   English

NLog中的自定义日志条目字符串格式?

[英]Custom log entry string formatting in NLog?

I'm new to NLog and wanted to know if there's a way I write log entries formatted in some custom way?我是 NLog 的新手,想知道是否有办法编写以某种自定义方式格式化的日志条目? For example, here are some things I want to do to my log entries:例如,这里有一些我想对我的日志条目做的事情:

--> Have nested log entry messages (excluding log entry metadata) to make the depth of the logging call stack easier to follow. --> 具有嵌套的日志条目消息(不包括日志条目元数据),以使日志调用堆栈的深度更易于跟踪。 This can be done by indenting the log entry string proportionally by how deep you are in the logging call stack这可以通过按您在日志调用堆栈中的深度按比例缩进日志条目字符串来完成

--> Log a "change ID" (basically some sort of ID linked to some request that's being processed) with all relevant log entries --> 使用所有相关的日志条目记录一个“更改 ID”(基本上是与正在处理的某个请求相关联的某种 ID)

I know NLog has some templates you can use and stuff, but I would prefer having more control, in the form of a custom formatting class or something, which would intercept the logging request every time I do Log.Info(...) , and then format my log entry string appropriately according to the behavior I choose.我知道 NLog 有一些您可以使用的模板和东西,但我希望有更多的控制,以自定义格式 class 或其他东西的形式,它会在我每次执行Log.Info(...)时拦截日志记录请求,然后根据我选择的行为适当地格式化我的日志条目字符串。

Is this possible?这可能吗?

EDIT:编辑:

Here's the contents of my current NLog.config file:这是我当前的 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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="true" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
   <targets>
      <target name="logfile" xsi:type="File" fileName="logfile.log" />
      <target name="logconsole" xsi:type="Console" />
   </targets>
   <rules>
      <logger name="*" minlevel="Trace" writeTo="logconsole" />
      <logger name="*" minlevel="Trace" writeTo="logfile" />
   </rules>
</nlog>

One way is create a custom layout renderer.一种方法是创建自定义布局渲染器。

There are 2 options to do this:有 2 个选项可以做到这一点:

Lambda method Lambda 方法

Create a lambda methods and register before loading other NLog things (beware of statics), eg in main().创建一个 lambda 方法并在加载其他 NLog 内容(注意静态)之前注册,例如在 main() 中。

The lambda receives a LogEventInfo , which includes the following properties: Level, Message (unformated), FormattedMessage, Parameters (send to Log.Info), optional Exception and properties (named parameters) lambda 接收一个LogEventInfo ,其中包括以下属性:Level、Message(未格式化)、FormattedMessage、Parameters(发送到 Log.Info)、可选 Exception 和 properties(命名参数)

//Create ${message-length}

// NLog 4.7+ syntax
NLog.LogManager.Setup().SetupExtensions(s =>
   s.RegisterLayoutRenderer("message-length", (logevent) => logEvent.FormattedMessage.Length)
);

Class Class

If you need more control and options, you could also create a class that inherits from NLog.LayoutRenderers.LayoutRenderer如果您需要更多控制和选项,您还可以创建一个继承自 NLog.LayoutRenderers.LayoutRenderer 的 class

1. Setup 1. 设置

/// <summary>
/// E.g. usage:  ${MyFormatter:MyLayout:${uppercase}} or ${MyFormatter:${uppercase}}
/// </summary>
[LayoutRenderer("MyFormatter")]
public class MyFormatterLayoutRenderer: LayoutRenderer
{
    [RequiredParameter]
    public Layout MyLayout { get; set; }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        var text = MyLayout.Render(logEvent);
        builder.Append(text);
    }
}

2. Register 2.注册

You need to register the layout renderer :您需要注册布局渲染器

// NLog 4.7+ syntax
NLog.LogManager.Setup().SetupExtensions(s =>
   s.RegisterLayoutRenderer<MyNamespace.MyFormatterLayoutRenderer>("MyFormatter")
);

3. Usage三、用法

Use it as follows, set the layout attribute of a target.如下使用它,设置一个目标的布局属性。 For example:例如:

<target name="logfile" xsi:type="File" fileName="logfile.log" layout="${message-length} - ${level} - ${message} - ${exception}"  />
<target name="logconsole" xsi:type="Console" layout="${message-length} - ${level} - ${message} - ${exception}" />

Read more here 在这里阅读更多

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

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