NLog自定义LayoutRenderer用于范围缩进

时间:2011-05-10 13:49:37

标签: c# logging nlog

任何人都可以为nlog提供一个非常样本的自定义layoutrenderer吗?

我想通过示例

进行日志记录缩进

如果我从方法C调用方法B

文本日志文件如下:

Inside Method C
       Inside Method B

等等。

1 个答案:

答案 0 :(得分:7)

这里是:

[LayoutRenderer("IndentationLayout")]
public sealed class IndentationLayoutRenderer : LayoutRenderer
{
    // Value to substract from stack count
    private uint _ignore = 12;

    // Value to pad with.
    private string _ipadding = "| ";

    /// <summary>Set the number of (top) stackframes to ignore</summary>
    public uint Ignore
    {
        get { return _ignore; }
        set { _ignore = value; }
    }

    /// <summary>Set the padding value</summary>
    public string IndentationPadding
    {
        get { return _ipadding; }
        set { _ipadding = value; }
    }

    protected override void Append(StringBuilder builder, LogEventInfo ev)
    {
        // Get current stack depth, insert padding chars.
        StackTrace st = new StackTrace();
        long indent = st.FrameCount;
        indent = indent > _ignore ? indent - _ignore : 0;
        for (int i = 0; i < indent; ++i)
        {
            builder.Append(_ipadding);
        }
    }
}

注册:

if(NLog.Config.ConfigurationItemFactory.Default.LayoutRenderers.AllRegisteredItems.ContainsKey(
                "IndentationLayout"))
                return;

NLog.Config.ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("IndentationLayout", typeof(IndentationLayoutRenderer));