How to hook interceptor for ILogger - castle-windsor

I'm using the LoggingFacility, and need to add interceptor for the ILogger instances, created by the facility.
So far I tried to modify the component model for ILogger, and this didn't work, as the loggers are not really resolved using the standard resolving mechanism (they are created by a factory, which use some wrappers).
I was thinking to override the logging subresolver, but kernel.Resolver does not allow replacing (or wrapping) the resolver added by the facility.
I was thinking about hooking to Kernel.DependencyResolving, but it appears I can not replace the dependency there.
What is the most appropriate place to put such a hook, so I can add Interceptor for the ILogger.
EDIT: After a lot of poking around, I came with somewhat "hackish" solution, which unfortunately depends on small reflection usage.
The real problem appears to be, that the way the loggers are constructed does not follow (for me) the castle spirit of doing things. I.e. the resolver does not use the already registered logger factory, so it's impossible to add interceptors to the factory itself.

There is a great article about that on CodeProject: Aspect Oriented Programming (AOP) in C# using Castle DynamicProxy from Linjith Kunnon. It shows you how to define a Interceptor
public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var methodName = invocation.Method.Name;
try
{
Console.WriteLine(string.Format("Entered Method:{0}, Arguments: {1}", methodName, string.Join(",", invocation.Arguments)));
invocation.Proceed();
Console.WriteLine(string.Format("Sucessfully executed method:{0}", methodName));
}
catch (Exception e)
{
Console.WriteLine(string.Format("Method:{0}, Exception:{1}", methodName, e.Message));
throw;
}
finally
{
Console.WriteLine(string.Format("Exiting Method:{0}", methodName));
}
}
}
And how to register it with Castle.Windsor
kernel.Register(
Component.For<LoggingInterceptor>()
.ImplementedBy<LoggingInterceptor>()
);
kernel.Register(
Component.For<IRocket>()
.ImplementedBy<Rocket>()
.Interceptors(InterceptorReference.ForType<LoggingInterceptor>()).Anywhere
);
Please note that there is more valuable content in the linked article and that the whole code provided here is from the article and not from me. All kudos goes to Linjith Kunnon.

You need to create your own logger factory (derived from default implementation matching your logging framework) and then you can setup facility to use this factory like this:
container.AddFacility<LoggingFacility>(f => f.UseLog4Net().LogUsing<MyFactory>());
See full example here

Related

Is there a way to share #Before code between tests suite classes?

I am testing a Cordova plugin in Java/Android and I need to initialize my Plugin class and set some state before I run my Tests.
#Before
public void beforeEach() throws Exception {
System.out.println("Creating new Instance ");
PowerMockito.mockStatic(Helpers.class);
PowerMockito.when(Helpers.canUseStorage(any(), any())).thenReturn(true);
MyLogger myLoggerMock = PowerMockito.mock(MyLogger.class);
PowerMockito.doNothing().when(myLoggerMock, "log", anyString());
PowerMockito.whenNew(MyLogger.class).withAnyArguments().thenReturn(myLoggerMock);
this.sut = spy(new FilePicker());
PowerMockito.doNothing().when(this.sut).pick(any(), any());
}
I want to create a Test Suite / Java Class per public function, but I do not want to repeat that code every time.
Is there a way to share that before each between test suites? I have found ClassRule but I think I do not do what I need (or I am understanding it wrong... I am really new in Java)
In Typescript we can share beforeEachfunctions with several suites, and each suite can have their own beforeEach
One possible ways is using inheritance:
Make all test classes extend from one "parent test" class and define a #Before in a parent class.
So it will be called automatically for all the subclasses:
public class ParentTest {
#Before
public void doInitialization() {
....
}
}
public class Test1Class extends ParentClass {
#Test
public void fooTest() {
// doInitialization will be executed before this method
}
#Test
public void barTest() {
// doInitialization will be executed before this method as well
}
}
Two notes:
Note 1
In the code you use sut (subject under test) - this obviously should not be in the parent's doInitialization method, so its possible that Test1Class will also have methods annotated with #Before (read here for information about ordering and so forth)
Then the `sut gets initialized with Spy which is frankly weird IMHO, the Subject Under Test should be a real class that you wrote, but that's beyond the scope of the question, just mentioning it because it can point on mistake.
Note 2
I'm writing it in an an attempt to help because you've said that you're new in Java, this is not strictly related to your question...
While this approach works in general you should be really cautious with PowerMockito. I'm not a PowerMockito expert and try to avoid this type of mocks in my code but in a nutshell the way it manipulates the byte code can clash with other tools. From your code: you can refactor the HelperUtils to be non-static and thus avoid PowerMocking in favor of regular mocking which is faster and much more safe.
As for the Logging - usually you can compromise on it in unit test, if you're using slf4j library you can config it to use "no-op" log for tests, like sending all the logging messages into "nothing", and not-seeing them in the console.

How to get back MDC "inheritance" with modern logback?

After going back to an older project and getting around to update its dependencies I had to realize that logback does not anymore propagate MDCs to children since version 1.1.5: https://github.com/qos-ch/logback/commit/aa7d584ecdb1638bfc4c7223f4a5ff92d5ee6273
This change makes most of the logs nigh useless.
While I can understand the arguments given in the linked issues, I can not understand why this change could not have been made in a more backwards compatible manner (as is generally usual in java..).
Q: What is the now correct way to achieve the same behaviour other than having to subclass everything from Runnables to Threads?
I see no straightforward way to change this back. Two alternatives that come to mind are:
Way #1: Wrap all Runnables
Introduce an abstract class that will copy MDC from the original Thread to a new Thread and use it instead of Runnable
public abstract class MdcAwareRunnable implements Runnable
{
private Map<String, String> originalMdc;
public MdcAwareRunnable()
{
this.originalMdc = MDC.getCopyOfContextMap();
}
#Override
public void run()
{
MDC.setContextMap(originalMdc);
runImpl();
}
protected abstract void runImpl();
/**
* In case some Runnable comes from external API and we can't change that code we can wrap it anyway.
*/
public static MdcAwareRunnable wrap(Runnable runnable)
{
return new MdcAwareRunnable()
{
#Override
protected void runImpl()
{
runnable.run();
}
};
}
}
If some Runnable comes from an external API that you can't change that code, use wrap helper method.
Drawback: need to analyze and change whole code.
Way #2: Mess with slf4j internals
Resurrect the original LogbackMDCAdapter implementation that uses InheritableThreadLocal from before that commit and put it somewhere in your code under some other name. Then somewhere around startup use reflection to override MDC.mdcAdapter property with and instance of that custom implementation. This is obviously a dirty hack but it saves a lot of troubles comparing to #1.
Note: for performance reasons it makes to inherit your resurrected version from existing LogbackMDCAdapter and just override all the methods with old implementation. See LoggingEvent.java and LogbackMDCAdapter.getPropertyMap internal method for some details.
Way #3: Mess with logback jar (even stranger alternative)
This sounds to me as a quite bad plan but for completness here it is.
Again resurrect the original LogbackMDCAdapter but this time don't rename, compile it and override that .class file inside logback.jar.
Or resurrect the original LogbackMDCAdapter with renaming, remove .class file for org.slf4j.impl.StaticMDCBinder from logback.jar and add your own class that will return resurrected version of LogbackMDCAdapter either to logback.jar or to your code. MDC seems to be bound to that class by name to create an implementation of MDCAdapter to use.
Or you can achieve similar result by using custom ClassLoader that would map org.slf4j.impl.StaticMDCBinder to your class instead of the one inside logback.jar. Note: this is probably impossible to achieve inside a Web-container that will add its own custom ClassLoaders.
Way 4: Misuse TurboFilter
ch.qos.logback.classic.Logger passes the logging event to a filter before passing it along to the appenders.
Way 5: Modify log Encoder / provider
Although this would mean the logging event is not updated, but the log output will be.

How can I handle exception raised during Castle Windsor optional property injection?

Castle Windsor 3.2 provides a cool addition that is Diagnostic logging in the container. This helped me redirect the container logs to a log4net log file that's being used to store the application logs.
What I'd like to do now is to be able to actually catch the Exception the container detects while injecting my optional property.
In my specific situation, an Oracle database error ORA-28000: the account is locked was being raised while Castle tried to execute my code to inject the Database property in a BaseController class:
public class BaseController : Controller
{
/// <summary>
/// Repository interface injected by Castle Windsor IoC container.
/// See <see cref="MyProject.Widgets.CastleWindsor.Facilities.PersistenceFacility.Init()"/> for more information.
/// </summary>
public ILogRepository Database { get; set; }
}
This Database property is null when I'm inside an action method in an Controller that inherits from BaseController. This all happens because Castle Windsor "swallows" the exception. The only message the user gets is: Object reference not set to an instance of an object. OK but I'd like to show the real exception/reason to the user, that is, ORA-28000: the account is locked. This message gets logged by Castle Windsor thanks to the aforementioned Diagnostic logging. This is cool but I want to be able to really catch the exception inside the catch block:
public class SubCatListController : BaseController
{
public ActionResult SubCatList(string subcat)
{
try
{
var sub = Database.GetLogSubCategory(subcat);
}
catch(Exception e) // I'd like to get the real exception from Castle Windsor here...
{
Logger.Error(e.Message, e);
}
}
}
Is this scenario possible with property injection?
As Krzysztof Kozmic mentioned in his comment we should not have any code that tries to do external object initialization while injecting a property.
My problem as I describe in this subsequent comment was that I was trying to open a database connection while initializing the property.
I removed that code and now the exception is only raised in my own domain code when that injected property is used for the 1st time.
Today I hit this same problem: one thing that helped me figure out the error was to momentarily use Constructor injection instead, like this:
private OEVizion _database;
public ReportingPeriodsController(OEVizion database)
{
_database = database;
}
Doing this I was able to see what was the error: version mismatch between log4net - the one in the OEVizion class library and the one used in the .Web project.
After getting the EF context correctly initialized I got back to Property injection and I'm back in business. :D
When you have optional dependencies it is always better to use the Null Object pattern.
public BaseController() {
Database = NullLogRepository.Instance;
}
It prevent the NullReferenceException and you can provide behavior you expect (do nothing, throw specific exception, log to trace etc.)

Castle Dynamic Proxy in Windsor Container

I've got a bit of a problem. I'm working in the Castle Windsor IOC Container. Now what i wanted to do is just mess about with some AOP principles and what i specifically want to do is based on a method name perform some logging. I have been looking at Interceptors and at the moment i am using the IInterceptor interface implemented as a class to perform this logging using aspects. The issue is if i want to perform the logging on a specific method then it gets messy as i need to put in some logic into my implemented aspect to check the method name etc...
I have read that you can do all of this using Dynamic Proxies and the IInterceptorSelector interface and the IProxyGenerationHook interface. I have seen a few examples of this done on the net but i am quite confused how this all fits into the Windsor container. I mean i am using the windsor container which in my code is actually a ref to the IWindsorContainer interface to create all my objects. All my configuration is done in code rather than XML.
Firstly does anyone know of a way to perform method specific AOP in the windsor container besides the way i am currently doing it.
Secondly how do i use the Dynamic Proxy in the windsor container ?
Below i have added the code where i am creating my proxy and registering my class with
the interceptors
ProxyGenerator _generator = new ProxyGenerator(new PersistentProxyBuilder());
IInterceptorSelector _selector = new CheckLoggingSelector();
var loggingAspect = new LoggingAspect();
var options = new ProxyGenerationOptions(new LoggingProxyGenerationHook())
{ Selector = _selector };
var proxy = _generator.CreateClassProxy(typeof(TestClass), options, loggingAspect);
TestClass testProxy = proxy as TestClass;
windsorContainer.Register(
Component.For<LoggingAspect>(),
Component.For<CheckLoggingAspect>(),
Component.For<ExceptionCatchAspect>(),
Component.For<ITestClass>()
.ImplementedBy<TestClass>()
.Named("ATestClass")
.Parameters(Parameter.ForKey("Name").Eq("Testing"))
.Proxy.MixIns(testProxy));
The Test Class is below:
public class TestClass : ITestClass
{
public TestClass()
{
}
public string Name
{
get;
set;
}
public void Checkin()
{
Name = "Checked In";
}
}
as for the interceptors they are very simple and just enter a method if the name starts with Check.
Now when i resolve my TestClass from the container i get an error.
{"This is a DynamicProxy2 error: Mixin type TestClassProxy implements IProxyTargetAccessor which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to mix in an existing proxy?"}
I know i'm using the proxy in the wrong way but as i haven't seen any concrete example in how to use a proxy with the windsor container it's kind of confusing.
I mean if i want to use the LoggingProxyGenerationHook which just tell the interceptors to first for methods that start with the word "check" then is this the correct way to do it or am i completely on the wrong path. I just went down the proxy way as it seems very powerfull and i would like to understand how to use these proxies for future programming efforts.
By using .Interceptors() you already are using Dynamic Proxy. When component has specified interceptors Windsor will create proxy for it, and use these interceptors for it. You can also use method .SelectedWith and .Proxy property to set other options you already know from DynamicProxy.
I just added a website about Windsor AOP to documentation wiki. There's not much there yet, but I (and Mauricio ;) ) will put there all the information you need. Take a look, and let us know if everything is clear, and if something is missing.

Fluent Interfaces - Method Chaining

Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.