In order to log user attempts to login to my web application, I need to save each attempt to a text file . I create a logger model as following:
public class Logger
{
public string name { get; set; }
public string date { get; set; }
public string ipAddress{ get; set; }
}
here is the login model that I need to create the logger for:
public class LoginModel
{
[Display(Name = "User Name")]
public string Username{ get; set; }
public string Password { get; set; }
}
The method to validate the user login in the controller is as following:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var loginResult = securityService.Login(model);
if (!string.IsNullOrEmpty(loginResult.ErrorMessage))
{
ModelState.AddModelError(string.Empty,
loginResult.ErrorMessage);
return View(model);
}
else
{
authManager.SignIn(claimsIdentity);
HttpOnly = true
});
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
}
I want to reuse the method above to write to a text file to store information such as the user name that was input to the view. any advice?
I would suggest you to use Nlog. I have used the same in my project and it works awesome. You need to create an object for it and you can use it straightforward. Here is small sample for it:
Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("Error while exporting QE reportlet from Dashboard -" + ex.Message + ex.StackTrace);
You need to install two packages Nlog and Nlog.config. After installing these you will see Nlog.config in your project. In that you will find a targets and rules tag and you need to modify them something like this:
<targets>
<target
name="logfile"
xsi:type="File"
fileName="D:\logging\mylogs.log"
archiveFileName="D:\logging\mylogs.{#}.log"
archiveNumbering="Date"
archiveEvery="Day"
archiveDateFormat="yyyyMMdd"
/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>