Nlog ${event-context:item=xxxx} not writing in logging database

后端 未结 3 2063
萌比男神i
萌比男神i 2021-01-24 05:11

I have a Nlog configuration that is basically this:

\">
  &         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 05:40

    As it turned out, it was a bug (or a feature) in NLog. When writing to a 'target' in NLog asynchronously the original LogEventInfo that is written is added to the Parameters collection of a new LogEventInfo, thus the Properties collection where the {event-context} gets its values from is empty (because it is a new object). Resulting in the empty strings written to the database.

    So, in order to solve this I added this function to << NLog 2.1 Source >>\Targets\Target.cs:

        private void MergeEventProperties(LogEventInfo logEvent)
        {
            foreach (var item in logEvent.Parameters)
            {
                if (item.GetType() == typeof(LogEventInfo))
                {
    
                    foreach (var propertyItem in ((LogEventInfo)item).Properties)
                    {
                        logEvent.Properties.Remove(propertyItem.Key);
                        logEvent.Properties.Add(propertyItem);
                    }
                }
            }
        }
    

    Then in the function protected virtual void Write(AsyncLogEventInfo logEvent) I changed this code

            try
            {
                this.Write(logEvent.LogEvent);
                logEvent.Continuation(null);
            }
    

    into this:

            try
            {
                MergeEventProperties(logEvent.LogEvent);
    
                this.Write(logEvent.LogEvent);
                logEvent.Continuation(null);
            }
    

    After that, my values were written to the database.

    I hope it helps other people who are having this issue.

提交回复
热议问题