<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dependency Injection Archives - Blog IT</title>
	<atom:link href="https://blogit.create.pt/category/development/dependency-injection/feed/" rel="self" type="application/rss+xml" />
	<link>https://blogit.create.pt/category/development/dependency-injection/</link>
	<description>Create IT blogger community</description>
	<lastBuildDate>Thu, 10 Jan 2019 12:46:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>
	<item>
		<title>log4net PatternLayout and PatternConverter</title>
		<link>https://blogit.create.pt/ricardocosta/2016/07/11/log4net-patternlayout-and-patternconverter/</link>
					<comments>https://blogit.create.pt/ricardocosta/2016/07/11/log4net-patternlayout-and-patternconverter/#respond</comments>
		
		<dc:creator><![CDATA[Ricardo Costa]]></dc:creator>
		<pubDate>Mon, 11 Jul 2016 16:50:58 +0000</pubDate>
				<category><![CDATA[log4net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[.NET]]></category>
		<guid isPermaLink="false">http://blogit.create.pt/ricardocosta/?p=1221</guid>

					<description><![CDATA[<p>I have the following scenario: I&#8217;m using Unity dependency injection container and interception techniques to log some WCF operation calls. I need to log the input parameters and also the result of these operations so I&#8217;ve implemented a CallHandler that I can apply to whatever methods that I need to intercept. In this CallHandler I&#8217;ve [&#8230;]</p>
<p>The post <a href="https://blogit.create.pt/ricardocosta/2016/07/11/log4net-patternlayout-and-patternconverter/">log4net PatternLayout and PatternConverter</a> appeared first on <a href="https://blogit.create.pt">Blog IT</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I have the following scenario:</p>
<p>I&#8217;m using <a href="https://github.com/unitycontainer/unity" target="_blank">Unity</a> dependency injection container and <a href="https://msdn.microsoft.com/en-us/library/dn178466(v=pandp.30).aspx" target="_blank">interception</a> techniques to log some WCF operation calls. I need to log the input parameters and also the result of these operations so I&#8217;ve implemented a <a href="https://msdn.microsoft.com/en-us/library/ff660871(v=pandp.20).aspx" target="_blank">CallHandler</a> that I can apply to whatever methods that I need to intercept.</p>
<p>In this CallHandler I&#8217;ve defined a class called LogEntry and I&#8217;m logging with log4net. Something like this:</p>
<pre class="brush: csharp; title: ; notranslate">

LogEntry logEntry = new LogEntry();
....
// set some base properties
logEntry.MethodName = input.MethodBase.Name;
logEntry.TypeName = input.Target.GetType().FullName;
...
// set input parameters
logEntry.Input = ....;
...
// set return value
logEntry.ReturnValue = result.ReturnValue;
.....
// set total method duration
logEntry.CallTime = stopwatch.Elapsed.TotalMilliseconds;
.....

// use log4net logger to log this information
logger.Debug(logEntry);
</pre>
<p>So this LogEntry class has some properties that will hold the information that I want to log. Now I need to capture these properties and configure the log4net <a href="https://logging.apache.org/log4net/release/config-examples.html" target="_blank">appenders</a> properly.</p>
<p>I&#8217;m using log4net PatternLayout and PatternConverter features. Let&#8217;s start with PatternLayout</p>
<pre class="brush: csharp; title: ; notranslate">

///&lt;summary&gt;
/// Extended version of &lt;see cref=&quot;PatternLayout&quot;/&gt;
/// &lt;/summary&gt;


public class ExtendedPatternLayout : PatternLayout
{
 ///&lt;summary&gt;
 /// Initializes a new instance of the &lt;see cref=&quot;ExtendedPatternLayout&quot;/&gt; class.
 /// &lt;/summary&gt;;


 public ExtendedPatternLayout()
 {
   this.AddConverter(new ConverterInfo()
   {
     Name = &quot;logEntry&quot;,
     Type = typeof(LogEntryConverter),
   });
 }
}

</pre>
<p>This layout just adds a new Converter named &#8220;logEntry&#8221; implemented by the class LogEntryConverter. There is no reference to LogEntry class here. And the LogEntryConverter class is here:</p>
<pre class="brush: csharp; title: ; notranslate">

 /// &lt;summary&gt;
 /// Custom &lt;see cref=&quot;PatternConverter&quot;/&gt; to handle &lt;see cref=&quot;LogEntry&quot;/&gt;
 /// &lt;/summary&gt;
 public class LogEntryConverter : PatternConverter
 {
   /// &lt;summary&gt;
   /// Converts the specified writer.
   /// &lt;/summary&gt;
   /// &lt;param name=&quot;writer&quot;&gt;The writer.&lt;/param&gt;
   /// &lt;param name=&quot;state&quot;&gt;The state.&lt;/param&gt;
   protected override void Convert(System.IO.TextWriter writer, object state)
   {
       var loggingEvent = state as LoggingEvent;
       var logEntry = loggingEvent.MessageObject as LogEntry;

       if (logEntry != null)
       {
          switch (this.Option.ToLower())
          {
             case &quot;calltime&quot;:
               writer.Write(logEntry.CallTime.HasValue ? logEntry.CallTime.Value : 0);
               break;
             case &quot;methodname&quot;:
               writer.Write(logEntry.MethodName);
               break;
             case &quot;returnvalue&quot;:
               writer.Write(SerializationService.SerializeToJSON(logEntry.ReturnValue));
               break;
             ..........
             ..........
             default:
               writer.Write(string.Empty);
               break;
          }
       }
    }
 }

</pre>
<p>I&#8217;ve made the code smaller but you need to check for null references!</p>
<p>I&#8217;m using a JSON serialization technique to grab the representation of the method&#8217;s return value.</p>
<p>I need to override the Convert method and access state object that is a log4net <a href="https://logging.apache.org/log4net/log4net-1.2.13/release/sdk/log4net.Core.LoggingEvent.html" target="_blank">LoggingEvent</a> object. This object has my logged object from the CallHandler which is a LogEntry object. Based on the <a href="https://logging.apache.org/log4net/release/sdk/index.html" target="_blank">Option</a> property of the converter I can choose which property to write.</p>
<p>And finally I can configure my log4net like this</p>
<pre class="brush: xml; title: ; notranslate">

&lt;layout type=&quot;ExtendedPatternLayout&quot;&gt;
  &lt;conversionPattern value=&quot;%logEntry{CallTime}&quot; /&gt;
&lt;/layout&gt;

</pre>
<p>You can see the conversionPattern follows this syntax: %convertername{option}</p>
<p>The post <a href="https://blogit.create.pt/ricardocosta/2016/07/11/log4net-patternlayout-and-patternconverter/">log4net PatternLayout and PatternConverter</a> appeared first on <a href="https://blogit.create.pt">Blog IT</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogit.create.pt/ricardocosta/2016/07/11/log4net-patternlayout-and-patternconverter/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Add WCF Message Id in every log4net message</title>
		<link>https://blogit.create.pt/ricardocosta/2015/11/24/add-wcf-message-id-in-every-log4net-message/</link>
					<comments>https://blogit.create.pt/ricardocosta/2015/11/24/add-wcf-message-id-in-every-log4net-message/#respond</comments>
		
		<dc:creator><![CDATA[Ricardo Costa]]></dc:creator>
		<pubDate>Tue, 24 Nov 2015 20:14:06 +0000</pubDate>
				<category><![CDATA[log4net]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Unity]]></category>
		<guid isPermaLink="false">http://blogit.create.pt/ricardocosta/?p=871</guid>

					<description><![CDATA[<p>I needed to have the WCF message identifier in every log message because I needed to correlate the log messages from a particular WCF call. The best way to achieve this with log4net is to use context properties. Since I&#8217;m already using Unity and Interception on my WCF Services, I&#8217;ve decided to implement a custom Call [&#8230;]</p>
<p>The post <a href="https://blogit.create.pt/ricardocosta/2015/11/24/add-wcf-message-id-in-every-log4net-message/">Add WCF Message Id in every log4net message</a> appeared first on <a href="https://blogit.create.pt">Blog IT</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I needed to have the WCF message identifier in every log message because I needed to correlate the log messages from a particular WCF call.</p>
<p>The best way to achieve this with <a title="log4net" href="https://logging.apache.org/log4net/" target="_blank">log4net</a> is to use <a title="log4net context properties" href="https://logging.apache.org/log4net/release/manual/contexts.html" target="_blank">context properties</a>.</p>
<p>Since I&#8217;m already using <a title="Unity" href="https://github.com/unitycontainer/unity" target="_blank">Unity</a> and Interception on my WCF Services, I&#8217;ve decided to implement a custom <a title="Call Handler" href="https://msdn.microsoft.com/en-us/library/ff660871(v=pandp.20).aspx" target="_blank">Call Hander</a></p>
<pre class="brush: csharp; title: ; notranslate">

namespace CustomCallHandlers
{
 using System;
 using Microsoft.Practices.Unity.InterceptionExtension;

 /// &lt;summary&gt;
 /// Call Handler to setup wcf message id in log4net context
 /// &lt;/summary&gt;
 public class ServiceCallHandler : ICallHandler
 {
 /// &lt;summary&gt;
 /// The message identifier
 /// &lt;/summary&gt;
 private const string MessageIdKey = &quot;MessageId&quot;;

 /// &lt;summary&gt;
 /// Initializes a new instance of the &lt;see cref=&quot;ServiceCallHandler&quot;/&gt; class.
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;order&quot;&gt;The call handler's execution order.&lt;/param&gt;
 public ServiceCallHandler(int order)
 {
  this.Order = order;
 }

 /// &lt;summary&gt;
 /// Gets or sets the order.
 /// &lt;/summary&gt;
 public int Order { get; set; }

 /// &lt;summary&gt;
 /// Invokes the specified input.
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;input&quot;&gt;The input.&lt;/param&gt;
 /// &lt;param name=&quot;getNext&quot;&gt;The get next.&lt;/param&gt;
 /// &lt;returns&gt;The method return for the nexte invocation&lt;/returns&gt;
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
  if ((System.ServiceModel.OperationContext.Current != null) &amp;&amp;
      (System.ServiceModel.OperationContext.Current.IncomingMessageHeaders != null))
  {
   if (System.ServiceModel.OperationContext.Current.IncomingMessageHeaders.MessageId != null)
   {
    string messageId = System.ServiceModel.OperationContext.Current.IncomingMessageHeaders.MessageId.ToString();
    log4net.ThreadContext.Properties&#x5B;MessageIdKey] = messageId == &quot;(null)&quot; ? Guid.NewGuid().ToString() : messageId;
   }
  }

  IMethodReturn resultado = getNext()(input, getNext);

  // Cleaning
  log4net.ThreadContext.Properties&#x5B;MessageIdKey] = null;

  return resultado;
  }
 }
}

</pre>
<p>If you want to see how to configure log4net appenders to write custom properties check this <a title="Custom properties log4net" href="http://blogit.create.pt/ricardocosta/2015/11/23/custom-properties-log4net/" target="_blank">post</a>.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://blogit.create.pt/ricardocosta/2015/11/24/add-wcf-message-id-in-every-log4net-message/">Add WCF Message Id in every log4net message</a> appeared first on <a href="https://blogit.create.pt">Blog IT</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogit.create.pt/ricardocosta/2015/11/24/add-wcf-message-id-in-every-log4net-message/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
