I’m writing an ASP.NET MVC 3 application with lots of classes which are not web-specific. Because of strict requirement for audit trail, all suspicious activity should be logged with user ID and IP address.
How is this kind of logging usually done? Is the IP address only logged at the login controller? If so, how is the user ID passed to all the places where logging is necessary? Adding it as a parameter to each method doesn’t sound like a good idea.
I’m assuming by user id, you mean the identity of the authenticated user.
There is no need to pass this information since it is already available within your controllers.
For the current user:
User.Identity.NameFor the user’s IP address:
Request.UserHostAddressHowever, logging is typically application wide. You should create a logger interface that can be used by all areas of your application without needing a dependency on System.Web.
For example:
You can then create an implementation of this that calls into the current HttpContext to get the user identity and IP address.
Then whenever you need to log something (anywhere in your application) you just take a dependency on ILogger, which your IoC container can inject for you, and then just call
logger.Log("some message").Yes, this assumes you are using Dependency Injection and programming against interfaces, but then you should be 🙂