3

I am currently working on a project where we were wanting to add PostSharp functionality.

I have set up my Postsharp attribute as so

[Serializable]
public class NLogTraceAttribute : OnMethodBoundaryAspect
{
    private readonly string _logLevel;
    ILogger logger;

    public NLogTraceAttribute(string logLevel)
    {
        _logLevel = logLevel;

        logger = new Logger("TraceAttribute");
    }

    public override void OnEntry(MethodExecutionArgs args)
    {
        LogAction("Enter", args);
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        LogAction("Leave", args);
    }

    private void LogAction(string action, MethodExecutionArgs args)
    {
        var argumentsInfo = args.GetArgumentsInfo();

        logger.Log(_logLevel, "{0}: {1}.{2}{3}", action, args.Method.DeclaringType.Name, args.Method.Name, argumentsInfo);
    }
}

and trying to use it as

    [NLogTrace(NLogLevel.Debug)]

However when compiling the project I am getting the following error:

    Error   26  Cannot serialize the aspects: Type 'NLog.Logger' in Assembly 
    'NLog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c' 
    is not marked as serializable.. 

Any help would be appreciated

Thewads
  • 4,953
  • 11
  • 55
  • 71
  • Consider to use PostSharp-Diagnostics-Toolkit (http://www.sharpcrafters.com/blog/post/Configuring-PostSharp-Diagnostics-Toolkits.aspx) instead of writing own implementation. BTW, it's open source. – Michael Freidgeim Nov 01 '12 at 12:50

1 Answers1

5
[NonSerialized]
public Logger logger;

Declaring the logger as marked above has solved the problem I was having

Thewads
  • 4,953
  • 11
  • 55
  • 71
  • 1
    Are you really saying that this is working solution or you just typed it without running application? It could not work since even official documentation says that you should not use constructors of aspects for any initialization. There is `RuntimeInitialize` method for this. So in this case you should have NullPointerException inside LogAction, because logger was not created. – Vitalii Korsakov Jan 26 '13 at 07:45
  • This worked for me for adding NLog to my OnMethodBoundaryAspect for PostSharp -- thanks for the heads up! – Lance Larsen - Microsoft MVP Mar 21 '13 at 15:22