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.