I created a UserActivity Logging or Audit trail using ServiceFilter
. I couldn't use action filter as I need to pass the dependencies.
I successfully logged the activities of the user.
public class ActivityLog : ActionFilterAttribute
{
private ILogUserActivityService _service;
//injecting specified service to insert the log in database.
public ActivityLog(ILogUserActivityService service)
{
_service = service;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Stores the Request in an Accessible object
var request = filterContext.HttpContext.Request;
// Generate the log of user activity
LogUserActivity log = new LogUserActivity()
{
// Username. shall be changed to UserId later afteter Auth management.
UserName = filterContext.HttpContext.User.Identity.Name ?? "Anonymous",
// The IP Address of the Request
IpAddress = request.HttpContext.Connection.RemoteIpAddress.ToString(),
// The URL that was accessed
AreaAccessed = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(request),
// Creates Timestamp
TimeStamp = DateTime.Now
};
//saves the log to database
_service.SaveLog(log);
// Finishes executing the Action as normal
base.OnActionExecuting(filterContext);
}
}
I can add [ServiceFilter(typeof(ActivityLog))]
above the controller and this works perfectly.
Database record:
But now I would like to add more information. I will add one more column named "Description" where I shall be able to enter the description about what the user deleted, what changes he made, what did he add (along with few properties) and so on.
I am expecting something like Log.information(...)
in Serilog. So how can I achieve such thing?