Working with:
- .NET 4.5.1
- Web Forms
- Entity Framework 6 (Context Per Request)
- IIS 8, Windows 2012 Datacenter
Main concern: Thread safety and reliability.
The project consist of a closed system that will be used by numerous types of users which will execute various actions. In our current project I've decided to implement something that probably most developers find absolutely necessary.
There were serious problems in the past deriving from the lack of even the simplest logging system that would allow us to track some common user actions, especially manipulating data.
I know there are popular logging frameworks, but I want to achieve something relatively simple that will not block the main thread.
The idea was to pull all data I need while on the main thread, because it turned out some of the data was harder to access from a separate thread, and then create a task that will take care of the database insert. My knowledge of multi-threading is limited, and this is what I came-up with.
public static class EventLogger
{
public static void LogEvent(int eventType, string descr, Exception ex = null)
{
//Get the page that is currently being executed;
var executingPage = HttpContext.Current.CurrentHandler as Page;
string sourcePage = executingPage != null ? executingPage.AppRelativeVirtualPath : string.Empty;
var eventToAdd = new Event()
{
Date = DateTime.Now,
EventTypeId = eventType,
isException = ex != null ? true : false,
ExceptionDetails = ex != null ? ex.Message : string.Empty,
Source = sourcePage,
UserId = UserHelper.GetUserGuid(),
UserIP = UserHelper.GetUserIP(),
UserName = UserHelper.GetUserName(),
Description = descr
};
Task.Factory.StartNew(() => LogEventAsync(eventToAdd));
}
private static void LogEventAsync(Event eventToAdd)
{
using (var context = new PlaceholderEntities())
{
context.Events.Add(eventToAdd);
context.SaveChanges();
}
}
}
Questions:
- Would this be a good-enough way to log what I need and is it safe in a multi-user environment?
- How would you do it if you didn't want to dig into logging frameworks?