Write specific error to a text file?

I have a vb.NET program that sends out emails, and I need it to write to a log file when it can't send emails to certain addresses. I need it to tell me what day/time, and what email address. I'm pretty new and I have never captured errors before. So far, I have the following error block:

If _mailCounter.Text < MaxMessages Then 'DONT OVERLOAD MAIL SERVER

Try

System.Web.Mail.SmtpMail.Send(MM)

Catch ex As Exception

Err.Clear()

End Try

End If

Any help is appreciated!!! Thanks!

Tory



Answer this question

Write specific error to a text file?

  • CHKA2

    Try adding the following into your catch block.  You'll need to replace emailAddr with the actual email address and update the path to the log file that you want to use. Also make sure that you import System.IO

        Using sw As StreamWriter = New StreamWriter(File.Open("MyLogFile", FileMode.Append))
          sw.WriteLine("Email to {0} failed at {1}: ", emailAddr, DateTime.Now, ex.Message)
        End Using
    


  • canuck81

    Hi Tory;

    Just configure a trace listener in you application configuration file. Trace listeners can be configured through your application configuration file and turned on or off. even more, you can have trace listners that write to log file or event log.

    Your configuration file should look like..

    <configuration>
     <system.diagnostics>
      <trace autoflush="false" indentsize="4">
       <listeners>
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="mylog.log" />
        <remove name="Default" />
       </listeners>
      </trace>
     </system.diagnostics>
    </configuration>

    Then your code should look something like...

    If _mailCounter.Text < MaxMessages Then 'DONT OVERLOAD MAIL SERVER

    Try

    System.Web.Mail.SmtpMail.Send(MM)

    Catch ex As Exception

    System.Diagonistics.Trace.WriteLine("Error Sending Message. error was: " + ex.Message) ' do not concatenate strings, use string builder instead

    Err.Clear()

    End Try

    End If



  • Soundbyte

    Or Simply use the my classe to append the message to the text file

    My.Computer.FileSystem.WriteAlltext("MyLogFile", "Email to " & emailAddr & " failed at : " & DateTime.Now & ":" & ex.Message, True)


  • Write specific error to a text file?