Sign in to follow this  
assainator

[.net] vb.net logger question

Recommended Posts

heey all, At the moment i have a logger* in my program. (* I don't know what it name is, it writes all actions to a file.) The only problem is: The data is only written to the file when it is closed properly. (streamWriter.close() (replace streamWriter with var name)) This is done when the application is end's as it should. But when the app crashes, the data is not written to the file and I can't find out what happend. my code
Public Class Logger
    Private _LogMessages As ULong = 0
    Private stream As IO.StreamWriter

    Public Sub OpenLog(ByVal file As String)
        stream = New IO.StreamWriter(file)
    End Sub

    Public Sub CloseLog()
        stream.Close()
    End Sub

    Public Sub Write(ByVal msg As String)
        If _LogMessages < 1000000 Then
            stream.Write(msg)
            _LogMessages += 1
        End If
    End Sub

    Public Sub WriteLine(ByVal msg As String)
        If _LogMessages < 1000000 Then
            stream.WriteLine(msg)
            _LogMessages += 1
        End If
    End Sub
End Class

in the app it would be used as: 1. when the app start's the first thing it does is opening the log. 2. the app is in the main loop and does what it should do, logs everything 3. the app quit's and closes the logger. But if the app crashes the 'stream' is not closed properly so the data is not written to the file. the question get's down to: What can i do to make sure the filestream is closed properly even if the app crashes? thanks in advance, assainator

Share this post


Link to post
Share on other sites
First quick answer:
Use the Flush method after each Write. That will solve your problem.

Second answer:

Have a look at the Tracing classes in .NET. There is a class that will do all of this for you by simply configuring it.

Share this post


Link to post
Share on other sites
Another solution is to use exception handling, by using the Try/Finally statements:


logger = New Logger()

Try
' Main application code here - try to enclose as much of it as possible
' by wrapping it as close to the entry point as possible
Finally
logger.CloseLog()
End Try



.. or implement IDisposable and use the Using statement:


Using logger As New Logger()
' Main application code here, as above
End Using

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this