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 < MaxMessagesThen'DONT OVERLOAD MAIL SERVER

Try

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

Catch exAs Exception

Err.Clear()

EndTry

EndIf

Any help is appreciated!!! Thanks!

Tory

[1209 byte] By [Tory] at [2007-12-24]
# 1

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

AhmedNagy at 2007-8-31 > top of Msdn Tech,Visual Basic,Visual Basic Language...
# 2

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

JaredParsonsMSFT at 2007-8-31 > top of Msdn Tech,Visual Basic,Visual Basic Language...
# 3

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)

spotty at 2007-8-31 > top of Msdn Tech,Visual Basic,Visual Basic Language...