Translate

Montag, 29. Juni 2015

Error-Logging in VB.Net

Public Sub WriteToLog(ByVal Text As String)
        Try
            If System.IO.Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory() & "log\") = False Then
                System.IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory() & "log\") 'Verzeichnis erstellen
            End If
            'Datum anpassen
            Dim CurrentDate_Month As String = ""
            If DateTime.Today.Month < 10 Then
                CurrentDate_Month = "0" & DateTime.Today.Month
            Else
                CurrentDate_Month = DateTime.Today.Month
            End If
            Dim CurrentDate_Day As String = ""
            If DateTime.Today.Day < 10 Then
                CurrentDate_Day = "0" & DateTime.Today.Day
            Else
                CurrentDate_Day = DateTime.Today.Day
            End If
            'Dateipfad anlegen:
            Dim Dateipfad As String = System.AppDomain.CurrentDomain.BaseDirectory() & "log\" & DateTime.Today.Year & "_" & CurrentDate_Month & "_" & CurrentDate_Day & "_" & ".txt"
            If System.IO.File.Exists(Dateipfad) = False Then
                Using LogFile As FileStream = File.Create(Dateipfad, 200, FileOptions.Asynchronous)
                    LogFile.Close()
                End Using
            End If
            'Datei öffnen
            Dim fs As FileStream = New FileStream(Dateipfad, FileMode.Append, FileAccess.Write)
            'Stream öffnen
            Dim w As StreamWriter = New StreamWriter(fs)
            'Anfügen am Ende
            w.BaseStream.Seek(0, SeekOrigin.End)
            'Zeilen schreiben
            w.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")
            'Daten anpassen für Log:
            w.WriteLine(CurrentDate_Day & "." & CurrentDate_Month & "." & DateTime.Today.Year & "-" & TimeOfDay)
            w.Write(Text)
            w.WriteLine()
            'Writer und Stream schließen
            w.Close()
            fs.Close()
        Catch ex As Exception
            MessageBox.Show(ex.ToString) 'Fehlermeldung ausgeben
        End Try
    End Sub

Keine Kommentare:

Kommentar veröffentlichen