Log writing for events performed by the Users in Asp.Net

Today we will learn about how to Log writing for events performed by the Users in Asp.Net.

For any (web/desktop) applications, it is equally important to track actions or events being performed by users with it’s working flow. Any system will be working properly as its designed to be worked, but to maintain user actions with some kind of additional useful information would be helpful for administrative user for many kind of business requirements. Let us understand this log tracking functionality with some basic example.

Here, I have made one demo page with one button. As of now, we will track the users, clicking this button, with time stamp and IP Address. All details will be written in one notepad file which is newly created on everyday with name of that particular date (i.e. creating notepad on 09-08-2015, would be named as 20150908.txt). Whenever button will be clicked, one entry will be added in that notepad file.

Log writing-1

Below is the code:

protected void btnwritelog_Click(object sender, EventArgs e)
        {
            try
            {
                #region Declaration
                string strMessage, strFilePath;
                StreamWriter Swrite;
                #endregion

                #region Writing message for log
                
                strMessage = "Button clicked - Time : " + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss") +
                    " - User : " + (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["User"])) ? Convert.ToString(Request.QueryString["User"]) : "No Name") +
                    " - IPAddress : " + Dns.GetHostAddresses(Dns.GetHostName())[1].ToString();

                #endregion

                #region Text file audit log
                strFilePath = AppDomain.CurrentDomain.BaseDirectory + "AuditLog\\";
                if (!Directory.Exists(strFilePath))
                {
                    Directory.CreateDirectory(strFilePath);
                }
                Swrite = new StreamWriter(strFilePath + DateTime.Now.ToString("yyyyMMdd") + ".txt", true);
                Swrite.WriteLine(strMessage);
                Swrite.Flush();
                Swrite.Close();
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Download sample: Log writing for events performed by the Users in Asp.Net

Don’f forgot to give your feedback, thanks 🙂

Leave a Reply