0
votes

I have a web api project am working on and i want to use logger to log all my controller in web api to a file.

[HttpGet]
    [Route("")]
    public IActionResult GetAllDocumentTempates()
    {
        try
        {
            var document = _doumentTemplate.GetLiteDocumentReportTemplates().ToList();
            var result = Mapper.Map<IEnumerable<LiteDocumentReportTemplateViewModel>>(document);
            return Ok(result);
        }
        catch (Exception ex)
        {
            String msgInnerExAndStackTrace = string.Format("{0}; Inner Ex: {1};  Stack Trace: {2}", ex.Message, ex.InnerException, ex.StackTrace);
            ExceptionLoggingService.Instance.WriteLog(string.Format("From frmDelivery.ConditionallyPrint():{0}", msgInnerExAndStackTrace));
            return BadRequest();
        }
    }

This is my ExceptionLoggingService.cs: This is the service that handle all the errors and logging to files for me

public class ExceptionLoggingService: ActionFilterAttribute
{
    // </ Singleton code
    // private fields
    private readonly FileStream _fileStream;
    private readonly StreamWriter _streamWriter;
    private static ExceptionLoggingService _instance;
    // public property
    public static ExceptionLoggingService Instance
    {
        get
        {
            return _instance ?? (_instance = new ExceptionLoggingService());
        }
    }
    //private constructor
    private ExceptionLoggingService()
    {
        _fileStream = File.OpenWrite(GetExecutionFolder() + "\\EasyAsFallingOffA.log");
        _streamWriter = new StreamWriter(_fileStream);
    }
    // <!-- Singleton code

    public void WriteLog(string message)
    {
        if (!HHSConsts.Logging) return;
        StringBuilder formattedMessage = new StringBuilder();
        formattedMessage.AppendLine("Date: " + DateTime.Now.ToString());
        formattedMessage.AppendLine("Message: " + message);
        _streamWriter.WriteLine(formattedMessage.ToString());
        _streamWriter.Flush();
    }
    private string GetExecutionFolder()
    {
        return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

    }
}

This is my EasyAsFallingOffA.log file output

Date: 6/23/2018 12:02:24 PM Message: From frmDelivery.ConditionallyPrint():Object reference not set to an instance of an object.; Inner Ex: ; Stack Trace: at ProcessFlowManager.Domain.Helpers.ModelFactory.Create(CalendarActivity cal) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.Domain\Helpers\ModelFactory.cs:line 1170 at ProcessFlowManager.Infrastructure.LogicImplementations.EfCalendarActivities.GetCalendarActivity(Int32 id) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.Infrastructure\LogicImplementations\EfCalendarActivities.cs:line 54 at ProcessFlowManager.API.Controllers.CalendarController.GetAllGeneratedDcument(Int32 id) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.API\Controllers\CalendarController.cs:line 79

Everything is working fine for all code above but all this code was implemented using tautology because i am repeating inside all my try and catch. I am new to AOP and am looking for a way to do this using AOP so i can just call it once inside my controller.

2
I need to implement this using Aspect Oriented Programming but have tried everything but all to no avail and i don't want to use third party - Wealsegun
I need some advice on this please and nobody should introduce third parties because its not free - Wealsegun

2 Answers

3
votes

After a lot of shuffling the internet trying to get answer to my question i have successfully logged all my exception without using third parties libraries like PostSharp, Log4File, Spring etc. Using

ActionFilterAttribute, IExceptionFilter

I was able to solve this and log all my exception for enterprise project with the following code

public class LatestErrorHandler : ActionFilterAttribute, IExceptionFilter
{
    private const string FILE_NAME = "Exception.log";
    private const string TRACE_FILE = "TraceLog.log";
    public Type _exceptionType;
    FileStream _fileStream;
    StreamWriter _streamWriter;
    IHostingEnvironment host;
    public LatestErrorHandler(Type exceptionType)
    {
       // _fileStream = File.OpenWrite(host.ContentRootPath + "\\wale.log");
        //_streamWriter = new StreamWriter(_fileStream);
        //_fileStream.Close();
        _exceptionType = exceptionType;
    }


    public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);
        using (FileStream fs=new FileStream(TRACE_FILE, FileMode.Append, FileAccess.Write))
        {
            using (BinaryWriter rite=new BinaryWriter(fs))
            {
                if (context.HttpContext.Response==null)
                {
                    string con = "No log";
                    rite.Write(con);
                }
                else
                {
                    Controller exValue = (Controller)context.Controller;
                    ControllerContext control = (ControllerContext)exValue.ControllerContext;
                    ///HttpMethodActionConstraint http = (HttpMethodActionConstraint)control.ActionDescriptor.ActionConstraints.;

                    rite.Write(
                                 "  Date Exception Occurred" + DateTime.Now.ToString() +
                                 "  Route " 
                                 +control.RouteData.DataTokens.Values
                                 +context.RouteData.Routers
                                 //+control.ActionDescriptor.ActionConstraints+ ":"+ http.HttpMethods
                                 + context.RouteData.Values.Keys
                                 + control.ActionDescriptor.ActionName
                                 +context.ActionDescriptor.RouteValues.Values+
                                 "  Parameter"
                                 + context.ActionDescriptor.Parameters 
                                 +context.ActionDescriptor.Properties+
                                 "  Controller" 
                                 + control.ActionDescriptor.ControllerName

                                           );
                }
            }
        }


    }





    public void OnException(ExceptionContext context)
    {
        var cont= context.Exception;
        //var contInner = context.Exception.InnerException;
        using (FileStream fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (BinaryWriter rite = new BinaryWriter(fs))
          {
                // context.Result actionResult = new context.Result();

                if (context.HttpContext.Response == null)
                {
                    string con = "no errroer  ";
                    rite.Write(con);
                }
                else
                {

                    rite.Write(
                        "Date Exception Occurred" + DateTime.Now.ToString() +
                        " Exceptions" + "Message: " + cont.Message +
                        " InnerException" + cont.InnerException +
                        " StackTrace" + cont.StackTrace+
                        "Response" + context.HttpContext.Response.StatusCode
                    );




                }

            }

        }

    }






    public override void OnActionExecuted(ActionExecutedContext context)
    {

        base.OnActionExecuted(context);
        var cont = context.Exception;
        //var contInner = context.Exception.InnerException;
        using (FileStream fs = new FileStream(FILE_NAME, FileMode.Append, FileAccess.Write))
        {
            using (BinaryWriter rite=new BinaryWriter(fs))
            {
                // context.Result actionResult = new context.Result();
               var type =  context.Result.GetType().Name;   //context.Result

                if(type == "BadRequestObjectResult" )
                {

                    BadRequestObjectResult cont2 = (BadRequestObjectResult)context.Result;


                    Exception exValue = (Exception) cont2.Value;
                    if (exValue.InnerException==null)
                    {
                        rite.Write(
                              "\n  Date Exception Occurred  " + DateTime.Now.ToString() +
                              "\n  Exceptions" + "Message: " + cont2.Value +
                             // "\n  InnerException  " + exValue.InnerException +
                              "\n  Message    " + exValue.Message +
                              "\n  StackTrace  " + exValue.StackTrace
                       //"Response" + context.HttpContext.Response.StatusCode
                       );
                    }
                    else
                    {
                        rite.Write(
                               "\n  Date Exception Occurred  " + DateTime.Now.ToString() +
                               "\n  Exceptions" + "Message: " + cont2.Value +
                               "\n  InnerException  " + exValue.InnerException +
                               "\n  Message    " + exValue.Message +
                               "\n  StackTrace  " + exValue.StackTrace
                        //"Response" + context.HttpContext.Response.StatusCode
                        );
                    }


                }






                else
                {
                    // log details without error.





                }

            }

        }

    }



}

with this class i used Aspect Oriented Programming(AOP) to successfully log all my exception to file in all my controller.

 [LatestErrorHandler(typeof(ExceptionContext))]
//[CustomLoggingAttirbute]
[Produces("application/json")]
[Route("api/Calendar")]
public class CalendarController : Controller
{
      ICalendarActivities calendarActivities;

    IHostingEnvironment IHostingEnvironment;

    string projectFolder = "";
    string fileRootPath = "";

    // private string projectRootFolder;
    public CalendarController(ICalendarActivities _calendarActivities)
    {
        calendarActivities = _calendarActivities;
    }

    [HttpGet]
    [Route("")]

    public IActionResult GetAllCalenderReportList()
    {
        try
        {
            var calendars = calendarActivities.GetCalendarActivities();
            var result = AutoMapper.Mapper.Map<IEnumerable<LiteCalendarViewModel>>(calendars);
            return Ok(result);
        }
        catch (Exception ex)

        {
            //string msginnerexandstacktrace = string.Format("{0}; inner ex: {1};  stack trace: {2}", ex.Message, ex.InnerException, ex.StackTrace);
            //ExceptionLoggingService.Instance.WriteLog(string.Format("from frmdelivery.conditionallyprint():{0}", msginnerexandstacktrace));
            return BadRequest(ex);
        }
    }

This is my output

Date Exception Occurred 7/2/2018 5:13:18 PM ExceptionsMessage: System.NullReferenceException: Object reference not set to an instance of an object. at ProcessFlowManager.Domain.Helpers.ModelFactory.Create(CalendarActivity cal) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.Domain\Helpers\ModelFactory.cs:line 1170 at ProcessFlowManager.Infrastructure.LogicImplementations.EfCalendarActivities.GetCalendarActivity(Int32 id) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.Infrastructure\LogicImplementations\EfCalendarActivities.cs:line 48 at ProcessFlowManager.API.Controllers.CalendarController.GetAllGeneratedDcument(Int32 id) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.API\Controllers\CalendarController.cs:line 83 InnerException
Message Object reference not set to an instance of an object. StackTrace at ProcessFlowManager.Domain.Helpers.ModelFactory.Create(CalendarActivity cal) in C:\Users\BABATUNDE\Documents\Visual Studio 2017\Projects\pcm-netcore\ProcessFlowManager.Domain\Helpers\ModelFactory.cs:line 1170

0
votes

You can use this link to get started : Aspect Oriented Programming Using C# and PostSharp

And Or This: Injecting Behaviors Before and After Method Execution

First Level :

1) Add Class your project With Named LoggingAspect

2) inheritance of OnMethodBoundaryAspect

3)so Implementation OnEntry,OnSuccess,OnExit,OnException

Like below Code:

    [PSerializable]
   public class LoggingAspect : OnMethodBoundaryAspect
   {

     public override void OnEntry(MethodExecutionArgs args)
     {
        Console.WriteLine("The {0} method has been entered.", args.Method.Name);
     }

     public override void OnSuccess(MethodExecutionArgs args)
     {
       Console.WriteLine("The {0} method executed successfully.", args.Method.Name);
     }

     public override void OnExit(MethodExecutionArgs args)
     {
        Console.WriteLine("The {0} method has exited.", args.Method.Name);
     }     

     public override void OnException(MethodExecutionArgs args)
     {
        Console.WriteLine("An exception was thrown in {0}.", args.Method.Name);
     }

    }

  static class Program
  {
      [LoggingAspect]
      static void Main()
      {
         Console.WriteLine("Hello, world.");
      }
   }

OutPut :

     The Main method has been entered.
     Hello, world.
     The Main method executed successfully.
     The Main method has exited.