Log4Net with castle windsor - c#-4.0

I am configuring logging for my application and for logging I am using log4net and castle windsor for DI.
I want logging framework to be wrap inside custom implementation so it can be changed in future.
public interface ICustomLogger
{
void Debug(object message, Exception ex = null);
void Info(object message, Exception ex = null);
void Warn(object message, Exception ex = null);
void Error(object message, Exception ex = null);
void Fatal(object message, Exception ex = null);
}
public class CustomLogger : ICustomLogger
{
private readonly log4net.ILog _log;
private readonly log4net.ILog _log1;
public CustomLogger()
{
//approach1
var stack = new StackTrace();
var frame = stack.GetFrame(1);
var method = frame.GetMethod();
Type type = method.DeclaringType;
_log = log4net.LogManager.GetLogger(type);
//approach2
var dtype = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
_log1 = log4net.LogManager.GetLogger(dtype);
}
public CustomLogger(string name)
{
_log = log4net.LogManager.GetLogger(name);
}
public CustomLogger(Type type)
{
_log = log4net.LogManager.GetLogger(type);
}
public void Debug(object message, Exception ex = null)
{
if (_log.IsDebugEnabled)
{
if (ex == null)
{
_log.Debug(message);
}
else
{
_log.Debug(message, ex);
}
}
}
public void Info(object message, Exception ex = null)
{
if (_log.IsInfoEnabled)
{
if (ex == null)
{
_log.Info(message);
}
else
{
_log.Info(message, ex);
}
}
}
public void Warn(object message, Exception ex = null)
{
if (_log.IsWarnEnabled)
{
if (ex == null)
{
_log.Warn(message);
}
else
{
_log.Warn(message, ex);
}
}
}
public void Error(object message, Exception ex = null)
{
if (_log.IsErrorEnabled)
{
if (ex == null)
{
_log.Error(message);
}
else
{
_log.Error(message, ex);
}
}
}
public void Fatal(object message, Exception ex = null)
{
if (_log.IsFatalEnabled)
{
if (ex == null)
{
_log.Fatal(message);
}
else
{
_log.Fatal(message, ex);
}
}
}
}
To register this custom implementation with DI...
container.Register(Component.For<ICustomLogger>()
.ImplementedBy<CustomLogger>()
.LifeStyle.Transient);
Problem comes when I ask DI to resolve logger, then it always return logger for Customlogger type not the class where I want to use it.
class ABC
{
ICustomLogger _logger;
public ABC(ICustomLogger logger)
{
_logger = logger; // type of this logger is CustomLogger not ABC
}
}
Both the approach are not working to resolve logger as ABC.
Can anyone help me to understand what's wrong here and how to fix the issue.

You can do this via a custom dependency resolver.
You first need to create an implementation of ISubDependencyResolver that can resolve dependencies of type ICustomLogger:
public class LoggerResolver : ISubDependencyResolver
{
public bool CanResolve(
CreationContext context,
ISubDependencyResolver contextHandlerResolver,
ComponentModel model,
DependencyModel dependency)
{
//We can only handle dependencies of type ICustomLogger
return dependency.TargetType == typeof (ICustomLogger);
}
public object Resolve(
CreationContext context,
ISubDependencyResolver contextHandlerResolver,
ComponentModel model,
DependencyModel dependency)
{
//We pass the requested type, e.g. ABC, to the constructor of CustomLogger
return new CustomLogger(context.RequestedType);
}
}
You then need to register this resolver with the container like this:
container.Kernel.Resolver.AddSubResolver(new LoggerResolver());

For your specific question - in both approaches you never really leave the "scope" of your class. With the first you are creating a new StackTrace and in the other the declaring type of a constructor is that class itself.
But you implemented a constructor that can receive a type so why not use it. Currently your CustomLogger is registered with your default constructor:
//There is no place here that you tell castle to resolve using the constructor
//that receives `ABS`
container.Register(Component.For<ICustomLogger>()
.ImplementedBy<CustomLogger>()
.LifeStyle.Transient);
See Castle Windsor passing constructor parameters to understand how to pass the parameters and that way invoke the constructor you want
In addition - Worth re-thinking:
Though it is a good idea to create such abstraction between your code and external source in this case I would not do it and I will explain why:
From my experience one doesn't really change the logging framework after the code is up and running. Especially since you are working with a mature and excellent framework - Log4Net. It has many built in abilities and is very adaptable for ones needs: From different formatting of the messaged to outputting the logs to different sources such as databases, files and if I'm not wrong there are also appenders for things like elastic search.
You are using Castle Windsor which has a good integration with Log4Net and has for you a ready made Logging Facility to Log4Net. See this question for how simple it is to add it.
Last point is that if you already write good SOLID code and pass your logger as ILogger to all the components (and not a specific implementation) all they will probably do is call the different Debug/Info/Warn/Error/Fatal methods - which any other mature logging framework will have. So on the day you will have to change (which I think won't happen) you can write an interface that looks like the Log4Net's interface and an implementation that will adapt that to your new logging framework.

Related

Convert log level (log4net)

I want to convert an INFO log level to a WARN if the INFO log message contains an exception. Is there anyway I can accomplish this? (I am integrating log4net in a .NET application)
Unless you already wrap your logging calls, in which case you could intercept the messages before passing them to log4net, your best bet would be to create your own appenders which promote log events as appropriate. As each appender subclass would need the exact same code I've created an extension method which does the actual promotion:
public static class AppenderExtensions
{
public static LoggingEvent Promote(this LoggingEvent loggingEvent)
{
if (loggingEvent.Level != Level.Info
|| loggingEvent.ExceptionObject == null)
{
return loggingEvent;
}
var data = loggingEvent.GetLoggingEventData(FixFlags.All);
data.Level = Level.Warn;
return new LoggingEvent(data);
}
}
public class PromotingAdoNetAppender : AdoNetAppender
{
protected override void Append(LoggingEvent loggingEvent)
{
base.Append(loggingEvent.Promote());
}
}
public class PromotingRollingFileAppender : RollingFileAppender
{
protected override void Append(LoggingEvent loggingEvent)
{
base.Append(loggingEvent.Promote());
}
}
Then all you need to do is to declare these appender types in your config:
<appender name="DatabaseAppender"
type="Your.Namespace.Here.PromotingAdoNetAppender">
…

Debugging Package Manager Console Update-Database Seed Method

I wanted to debug the Seed() method in my Entity Framework database configuration class when I run Update-Database from the Package Manager Console but didn't know how to do it. I wanted to share the solution with others in case they have the same issue.
Here is similar question with a solution that works really well.
It does NOT require Thread.Sleep.
Just Launches the debugger using this code.
Clipped from the answer
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
The way I solved this was to open a new instance of Visual Studio and then open the same solution in this new instance of Visual Studio. I then attached the debugger in this new instance to the old instance (devenv.exe) while running the update-database command. This allowed me to debug the Seed method.
Just to make sure I didn't miss the breakpoint by not attaching in time I added a Thread.Sleep before the breakpoint.
I hope this helps someone.
If you need to get a specific variable's value, a quick hack is to throw an exception:
throw new Exception(variable);
A cleaner solution (I guess this requires EF 6) would IMHO be to call update-database from code:
var configuration = new DbMigrationsConfiguration<TContext>();
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
This allows you to debug the Seed method.
You may take this one step further and construct a unit test (or, more precisely, an integration test) that creates an empty test database, applies all EF migrations, runs the Seed method, and drops the test database again:
var configuration = new DbMigrationsConfiguration<TContext>();
Database.Delete("TestDatabaseNameOrConnectionString");
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
Database.Delete("TestDatabaseNameOrConnectionString");
But be careful not to run this against your development database!
I know this is an old question, but if all you want is messages, and you don't care to include references to WinForms in your project, I made some simple debug window where I can send Trace events.
For more serious and step-by-step debugging, I'll open another Visual Studio instance, but it's not necessary for simple stuff.
This is the whole code:
SeedApplicationContext.cs
using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Data.Persistence.Migrations.SeedDebug
{
public class SeedApplicationContext<T> : ApplicationContext
where T : DbContext
{
private class SeedTraceListener : TraceListener
{
private readonly SeedApplicationContext<T> _appContext;
public SeedTraceListener(SeedApplicationContext<T> appContext)
{
_appContext = appContext;
}
public override void Write(string message)
{
_appContext.WriteDebugText(message);
}
public override void WriteLine(string message)
{
_appContext.WriteDebugLine(message);
}
}
private Form _debugForm;
private TextBox _debugTextBox;
private TraceListener _traceListener;
private readonly Action<T> _seedAction;
private readonly T _dbcontext;
public Exception Exception { get; private set; }
public bool WaitBeforeExit { get; private set; }
public SeedApplicationContext(Action<T> seedAction, T dbcontext, bool waitBeforeExit = false)
{
_dbcontext = dbcontext;
_seedAction = seedAction;
WaitBeforeExit = waitBeforeExit;
_traceListener = new SeedTraceListener(this);
CreateDebugForm();
MainForm = _debugForm;
Trace.Listeners.Add(_traceListener);
}
private void CreateDebugForm()
{
var textbox = new TextBox {Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both, WordWrap = false};
var form = new Form {Font = new Font(#"Lucida Console", 8), Text = "Seed Trace"};
form.Controls.Add(tb);
form.Shown += OnFormShown;
_debugForm = form;
_debugTextBox = textbox;
}
private void OnFormShown(object sender, EventArgs eventArgs)
{
WriteDebugLine("Initializing seed...");
try
{
_seedAction(_dbcontext);
if(!WaitBeforeExit)
_debugForm.Close();
else
WriteDebugLine("Finished seed. Close this window to continue");
}
catch (Exception e)
{
Exception = e;
var einner = e;
while (einner != null)
{
WriteDebugLine(string.Format("[Exception {0}] {1}", einner.GetType(), einner.Message));
WriteDebugLine(einner.StackTrace);
einner = einner.InnerException;
if (einner != null)
WriteDebugLine("------- Inner Exception -------");
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _traceListener != null)
{
Trace.Listeners.Remove(_traceListener);
_traceListener.Dispose();
_traceListener = null;
}
base.Dispose(disposing);
}
private void WriteDebugText(string message)
{
_debugTextBox.Text += message;
Application.DoEvents();
}
private void WriteDebugLine(string message)
{
WriteDebugText(message + Environment.NewLine);
}
}
}
And on your standard Configuration.cs
// ...
using System.Windows.Forms;
using Data.Persistence.Migrations.SeedDebug;
// ...
namespace Data.Persistence.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
// Migrations configuration here
}
protected override void Seed(MyContext context)
{
// Create our application context which will host our debug window and message loop
var appContext = new SeedApplicationContext<MyContext>(SeedInternal, context, false);
Application.Run(appContext);
var e = appContext.Exception;
Application.Exit();
// Rethrow the exception to the package manager console
if (e != null)
throw e;
}
// Our original Seed method, now with Trace support!
private void SeedInternal(MyContext context)
{
// ...
Trace.WriteLine("I'm seeding!")
// ...
}
}
}
Uh Debugging is one thing but don't forget to call:
context.Update()
Also don't wrap in try catch without a good inner exceptions spill to the console.
https://coderwall.com/p/fbcyaw/debug-into-entity-framework-code-first
with catch (DbEntityValidationException ex)
I have 2 workarounds (without Debugger.Launch() since it doesn't work for me):
To print message in Package Manager Console use exception:
throw new Exception("Your message");
Another way is to print message in file by creating a cmd process:
// Logs to file {solution folder}\seed.log data from Seed method (for DEBUG only)
private void Log(string msg)
{
string echoCmd = $"/C echo {DateTime.Now} - {msg} >> seed.log";
System.Diagnostics.Process.Start("cmd.exe", echoCmd);
}

Ninject 2.0 InRequestScope() causing me problems - dependencies not being disposed

I'm using Ninject 2.0 with an MVC 2/EF 4 project in order to inject my repositories into my controllers. I've read that when doing something like that, one should bind using InRequestScope(). When I do that, I get a new repository per request, but the old repositories aren't being disposed. Since the old repositories are remaining in memory, I get conflicts with multiple ObjectContexts existing at the same time.
My concrete repositories implement IDisposable:
public class HGGameRepository : IGameRepository, IDisposable
{
// ...
public void Dispose()
{
if (this._siteDB != null)
{
this._siteDB.Dispose();
}
}
}
And my Ninject code:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel kernel = new StandardKernel(new HandiGamerServices());
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
{
return base.GetControllerInstance(requestContext, controllerType);
// return null;
}
}
catch (HttpException ex)
{
if (ex.GetHttpCode() == 404)
{
IController errorController = kernel.Get<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
{
throw ex;
}
}
return (IController)kernel.Get(controllerType);
}
private class HandiGamerServices : NinjectModule
{
public override void Load()
{
Bind<HGEntities>().ToSelf().InRequestScope();
Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
Bind<ErrorController>().ToSelf().InRequestScope();
}
}
}
What am I doing wrong?
I'm quite sure that you are wrong about the guess that your objects are not disposed. This just does not happen when you think it will happen. But the fact that this does happen later should not give you any problems with ObjectContexts unless you are doing something wrong. With a high load you will have a lot of ObjectContexts at the same time anyway.
What can become a problem though is that the memory usage increases. That's why the request scope needs to be released actively. The Ninject MVC extensions will take care of that. Otherwise have a look at the OnePerRequestModule to see how it is done:
https://github.com/ninject/Ninject.Web.Common/blob/master/src/Ninject.Web.Common/OnePerRequestHttpModule.cs

How can I get this old Ninject 2 code to work with Ninject 3 and the MVC 2 extension (NinjectControllerFactory)?

In my MVC 2 project, I originally used Ninject 2 and wrote this version of the NinjectControllerFactory:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel kernel = new StandardKernel(new HandiGamerServices());
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
{
return base.GetControllerInstance(requestContext, controllerType);
// return null;
}
}
catch (HttpException ex)
{
if (ex.GetHttpCode() == 404)
{
IController errorController = kernel.Get<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
{
throw ex;
}
}
return (IController)kernel.Get(controllerType);
}
Of most importance is the retrieval of my ErrorController, which allows me to gracefully handle a multitude of HTTP errors.
The problem is that I upgraded to the MVC 2 extension via Nuget, so a NinjectControllerFactory is already provided. Would it be possible to use my own override of GetControllerInstance? If so, how?
I do exactly this, and for precisely the same reason. In Global.asax.cs, I add this to my OnApplicationStarted override (declared virtual in NinjectHttpApplication):
ControllerBuilder.Current.SetControllerFactory(
new MyControllerFactory(ControllerBuilder.Current.GetControllerFactory()));
This means you're creating your own controller factory, but providing it with the default implementation to do the heavy lifting.
Then define your controller factory like so:
public class MyControllerFactory : IControllerFactory
{
private IControllerFactory defaultFactory;
public MyControllerFactory(IControllerFactory defaultFactory)
{
this.defaultFactory = defaultFactory;
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
try
{
var controller = defaultFactory.CreateController(requestContext, controllerName);
return controller;
}
catch (HttpException e)
{
// Pasted in your exception handling code here:
if (ex.GetHttpCode() == 404)
{
IController errorController = kernel.Get<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
{
throw ex;
}
}
}
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
{
return defaultFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
public void ReleaseController(IController controller)
{
defaultFactory.ReleaseController(controller);
}
}
As you can see, we're just using the default (Ninject) controller factory for most purposes unless it can't find the page. For obtaining the error controller, you can either pass in the kernel as you were already doing, or just call defaultFactory.CreateController using the error controller name.

How to pass parameters to a CodeActivity in a NativeActivity code sequence

I'm trying to get windows workflows working, and I've become a little stumped.
I've gotten a single workflow working, but now I am trying to do something a little more complex: start a workflow, where each activity itself contains a workflow. (Picture something like the main program starts the activities "Input, logic, and output", and then each of those have additional activities like "prompt user, get input, etc.")
I've had it working fine, with the example from here (http://msdn.microsoft.com/en-us/magazine/gg535667.aspx), when I am not passing any parameters from the main program to the activites. My question is, how exactly does the 'Variables' and 'metadata.SetVariablesCollection' work in the NativeActivity, and how to I get the parameters to the low level activities?
This is what I am currently trying:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Collections.ObjectModel;
using System.Activities.Statements;
namespace Project1
{
internal class MainProgram
{
internal static void Main(string[] args)
{
try
{
var act = new SimpleSequence();
act.Activities.Add((Activity)(new WriteSomeText()));
act.Activities.Add((Activity)(new WriteSomeText()));
act.Activities.Add((Activity)(new WriteSomeText()));
act.Variables.Add(new Variable<string> ("stringArg", "TEXT"));
WorkflowInvoker.Invoke(act);
}
catch (Exception ex)
{
System.Console.WriteLine("EXCEPTION: {0}", ex);
}
}
public class WriteSomeText : CodeActivity
{
[RequiredArgument]
public InArgument<string> stringArg { get; set; }
protected override void Execute(CodeActivityContext context)
{
string output = context.GetValue(stringArg);
System.Console.WriteLine(output);
}
}
public class SimpleSequence : NativeActivity
{
Collection<Activity> activities;
Collection<Variable> variables;
Variable<int> current = new Variable<int> { Default = 0 };
public Collection<Activity> Activities
{
get
{
if (this.activities == null)
this.activities = new Collection<Activity>();
return this.activities;
}
set
{
this.activities = value;
}
}
public Collection<Variable> Variables
{
get
{
if (this.variables == null)
this.variables = new Collection<Variable>();
return this.variables;
}
set
{
this.variables = value;
}
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
metadata.SetChildrenCollection(this.activities);
metadata.SetVariablesCollection(this.variables);
metadata.AddImplementationVariable(this.current);
}
protected override void Execute(NativeActivityContext context)
{
if (this.Activities.Count > 0)
context.ScheduleActivity(this.Activities[0], onChildComplete);
}
void onChildComplete(NativeActivityContext context, ActivityInstance completed)
{
int currentExecutingActivity = this.current.Get(context);
int next = currentExecutingActivity + 1;
if (next < this.Activities.Count)
{
context.ScheduleActivity(this.Activities[next], this.onChildComplete);
this.current.Set(context, next);
}
}
}
}
}
This ends up throwing the following exception:
EXCEPTION: System.Activities.InvalidWorkflowException: The following errors were encountered while processing the workflow tree:
'WriteSomeText': Value for a required activity argument 'stringArg' was not supplied.
'WriteSomeText': Value for a required activity argument 'stringArg' was not supplied.
'WriteSomeText': Value for a required activity argument 'stringArg' was not supplied.
at System.Activities.Validation.ActivityValidationServices.ThrowIfViolationsExist(IList`1 validationErrors)
at System.Activities.Hosting.WorkflowInstance.ValidateWorkflow(WorkflowInstanceExtensionManager extensionManager)
at System.Activities.Hosting.WorkflowInstance.RegisterExtensionManager(WorkflowInstanceExtensionManager extensionManager)
at System.Activities.WorkflowApplication.EnsureInitialized()
at System.Activities.WorkflowApplication.RunInstance(WorkflowApplication instance)
at System.Activities.WorkflowApplication.Invoke(Activity activity, IDictionary`2 inputs, WorkflowInstanceExtensionManager extensions, TimeSpan timeout)
at System.Activities.WorkflowInvoker.Invoke(Activity workflow, TimeSpan timeout, WorkflowInstanceExtensionManager extensions)
at System.Activities.WorkflowInvoker.Invoke(Activity workflow)
at Project1.MainProgram.Main(String[] args) in c:\users\user\documents\visual studio 2010\Projects\ModelingProject1\Project1\MainProgram.cs:line 25
I know, I only pass 1 parameter, but the exception still says that I am missing 3 parameters. I am missing something as to how to do this properly.
You're correctly declaring stringArg as an InArgument but you're not passing any value to it when calling it inside SimpleSequence.
You can pass something using the constructor, while constructing the all activity itself, like this:
public class WriteSomeText : CodeActivity
{
[RequiredArgument]
public InArgument<string> stringArg { get; set; }
public WriteSomeText(string stringArg)
{
this.stringArg = stringArg;
}
protected override void Execute(CodeActivityContext context
{
string output = context.GetValue(stringArg);
System.Console.WriteLine(output);
}
}
// Calling the activity like this:
internal static void Main(string[] args)
{
var act = new SimpleSequence()
{
Activities =
{
new WriteSomeText("hello"),
new WriteSomeText("world"),
new WriteSomeText("!")
}
};
WorkflowInvoker.Invoke(act);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Also notice that is a best practice to use the constructor to initialize collections:
public SimpleSequence()
{
activities = new Collection<Activity>();
variables = new Collection<Variable>();
}
This way is even more intuitive to initialize the activity:
var act = new SimpleSequence()
{
Activities =
{
new WriteSomeText("hello"),
new WriteSomeText("world"),
new WriteSomeText("!")
},
Variables =
{
new Variable<int>("myNewIntVar", 10),
// ....
}
};
EDIT:
There are a couple of other ways to approach the problem. This is your best friend while starting in the WF4 world.
Check WF\Basic\CustomActivities\Code-Bodied for a little push with this particular case.

Resources