NLog custom LayoutRenderer for scope indentation

后端 未结 1 1531
天命终不由人
天命终不由人 2020-12-17 04:28

can any one provide me of a very sample custom layoutrenderer for nlog ?

I want to make indentation while im logging , by example

if im calling Method B fr

相关标签:
1条回答
  • 2020-12-17 04:51

    here it is:

    [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);
            }
        }
    }
    

    Registration:

    if(NLog.Config.ConfigurationItemFactory.Default.LayoutRenderers.AllRegisteredItems.ContainsKey(
                    "IndentationLayout"))
                    return;
    
    NLog.Config.ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("IndentationLayout", typeof(IndentationLayoutRenderer));
    
    0 讨论(0)
提交回复
热议问题