How to: Log Messages When the Application Starts or Shuts Down (Visual Basic)

You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This example shows how to use the My.Application.Log.WriteEntry method with the Startup and Shutdown events to write tracing information.

To access the application's event-handler code

  1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.

  2. Click the Application tab.

  3. Click the View Application Events button to open the Code Editor.

    This opens the ApplicationEvents.vb file.

To log messages when the application starts

  1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.

  2. On the Declarations menu, choose Startup.

    The application raises the Startup event before the main application runs.

  3. Add the My.Application.Log.WriteEntry method to the Startup event handler.

    My.Application.Log.WriteEntry("Application started at " &
        My.Computer.Clock.GmtTime.ToString)
    

To log messages when the application shuts down

  1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.

  2. On the Declarations menu, choose Shutdown.

    The application raises the Shutdown event after the main application runs, but before it shuts down.

  3. Add the My.Application.Log.WriteEntry method to the Shutdown event handler.

    My.Application.Log.WriteEntry("Application shut down at " &
        My.Computer.Clock.GmtTime.ToString)
    

Example

You can use the Project Designer to access the application events in the Code Editor. For more information, see Application Page, Project Designer (Visual Basic).

Private Sub MyApplication_Startup(
    ByVal sender As Object,
    ByVal e As ApplicationServices.StartupEventArgs
) Handles Me.Startup
    My.Application.Log.WriteEntry("Application started at " &
        My.Computer.Clock.GmtTime.ToString)
End Sub

Private Sub MyApplication_Shutdown(
    ByVal sender As Object,
    ByVal e As System.EventArgs
) Handles Me.Shutdown
    My.Application.Log.WriteEntry("Application shut down at " &
        My.Computer.Clock.GmtTime.ToString)
End Sub

See also