Search code examples
asp.netvb.netlogfiles

How to write to a log file on the website


I log actions to prove that certain tasks have been performed by specific users. Writing to a log file works in the development space (writing to C:\CPLogfile\ on my PC), but as soon as I publish the solution, I get the following error:

Server Error in '/' Application

My Code:

Public Sub LogAction(WhoIsThis As String, MessageToLog As String)

    Dim ThisPath As String = HttpContext.Current.Request.Url.Host
    Dim LogfileName As String = "logAction" & Format(Now(), "yyyyMMdd") & ".txt"
    If InStr(ThisPath, "localhost") > 0 Then '----- Local machine
        LogfileName = "C:\CPLogfile\" & LogfileName
        If Not Directory.Exists("C:\CPLogfile") Then
            Directory.CreateDirectory("C:\CPLogfile\")
        End If
    Else
        LogfileName = ThisPath & "logAction" & Format(Now(), "yyyyMMdd") & ".txt"
    End If
    Using w As StreamWriter = File.AppendText(LogfileName)
        w.Write("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
        w.WriteLine(", User: " & WhoIsThis)
        w.WriteLine("  :{0}", MessageToLog)
        w.WriteLine("-------------------------------")
    End Using
End Sub

Solution

  • The main reason you cannot work outside of the IIS directories by default is a security issue. It stops things like transversal attacks. The reason you can on a development machine is most likely you are not using the full IIS product. When you move to IIS, you are restricted.

    You have a couple of options:

    1. Convince people to let you turn off the feature in IIS and open up a security hole in your server
    2. Log to a database instead
    3. Create a WCF service that writes the log file and set it up so it is not using IIS

    There are other options, but these are the three easiest. The easiest is number 1, as it is a setting in IIS. I also would not recommend this solution.