I am planning to use a shared variable to implement a logging facility. Have a look at the code below:
Imports System.IO
Public Class TestClass
Public Shared objError As New StreamWriter("C:\Test.txt")
End Class
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
TestClass.objError.WriteLine("Error 1")
TestClass.objError.WriteLine("Error 2")
TestClass.objError.WriteLine("Error 3")
'TestClass.objError.Close()
TestClass.objError.WriteLine("Error 4")
TestClass.objError = Nothing
Catch ex As Exception
End Try
End Sub
I don’t understand how this shared variable is created and destroyed (I assume it is created before the form_load and destroyed by the form_unload). I also don’t understand why it is possible to set the reference to the static variable to Nothing; surely the variable should exist until the program ends? (Q1, part 1) I realise this is a simple question.
Is there a better way to implement a logging mechanism? (Q1 part 2). The logging mechanism writes errors and log entries.
UPDATE
I think I have found my answer here: http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx. “A static variable continues to exist and retains its most recent value. The next time your code calls the procedure, the variable is not reinitialized, and it still holds the latest value that you assigned to it. A static variable continues to exist for the lifetime of the class or module that it is defined in.”
I am not convinced that this is the best way to create a logging facility. Therefore part 2 to my question is still open.
You’re confusing between the area of memory reserved for the variable
Public Shared objErrorand the instance of an object created and assigned to this areaAs New StreamWriter("C:\Test.txt").
When you declare the variable
objError, the compiler reserves the memory required, but doesn’t fill it with a valid value (an instance of an object).Is the New command that initializes this area with an object instance of a StreamWriter.
When you assign to the variable the value Nothing you are wiping the instance of the StreamWriter (really I prefer to call explicitily Flush and Close), but you are not deleting the area of memory reserved for the Shared variable.
Regarding the log. You ask ‘which is the best way’ then the best method is to use an external component as you have been recommended. It will be very difficult to create a better logging system, log4net has been tried and tested, it’s free and it is considered the best.