Enviando email com Log4Net
Autor: Clayr Madeira | Publicado: 2011-10-27T16:56:00-07:00

<!--[if gte mso 9]>     Normal   0   21         false   false   false                             MicrosoftInternetExplorer4   <![endif]--><!--[if gte mso 9]>     <![endif]--><!--[if gte mso 10]> 
 /* Style Definitions */
 table.MsoNormalTable
 {mso-style-name:"Tabela normal";
 mso-tstyle-rowband-size:0;
 mso-tstyle-colband-size:0;
 mso-style-noshow:yes;
 mso-style-parent:"";
 mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
 mso-para-margin:0cm;
 mso-para-margin-bottom:.0001pt;
 mso-pagination:widow-orphan;
 font-size:10.0pt;
 font-family:"Times New Roman";
 mso-ansi-language:#0400;
 mso-fareast-language:#0400;
 mso-bidi-language:#0400;}
 <![endif]-->  Continuando a seqüência de publicações sobre o framework Log4Net, vamos mostrar a configuração necessária para que o Log4Net envie mensagens de email com a mensagem da aplicação. Vamos usar o projeto inicial que pode ser baixado aqui.
Abrindo o arquivo web.config vamos mudar nossa chave do Log4Net acrescentando a configuração da conta de email que vai enviar e receber as mensagens. Lembrando que com essa framework é possível ter varias configurações, possibilitando salvar o arquivo em disco e enviar email simultaneamente.
Vamos deixar nossa chave da seguinte forma:
&nbsp; <!--<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:green;mso-ansi-language:EN-US" lang="EN-US">Log4Net<span style="font-size:9.5pt;font-family:Consolas;mso-bidi-font-family:
Consolas;color:blue;mso-ansi-language:EN-US" lang="EN-US">-->&nbsp; &lt;log4net&gt;&nbsp;&nbsp;&nbsp; <!--<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:green;mso-ansi-language:EN-US" lang="EN-US">Envia no Email<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:blue;mso-ansi-language:EN-US" lang="EN-US">-->&nbsp;&nbsp;&nbsp; &lt;appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;to value="clayr@servidor.com.br" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;from value="clayr@servidor.com.br" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;subject value="Titulo - Ocorreu um Erro" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;authentication value="1" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;username value="clayr@servidor.com.br" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;password value="minhasenha" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;smtpHost value="201.10.10.1" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;bufferSize value="1" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;port value="587"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;layout type="log4net.Layout.SimpleLayout" /&gt;&nbsp;&nbsp;&nbsp; <!--appender&gt;&nbsp;&nbsp;&nbsp; <!--<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:green;mso-ansi-language:EN-US" lang="EN-US">Salva em Arquivo<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:blue;mso-ansi-language:EN-US" lang="EN-US">-->&nbsp;&nbsp;&nbsp; &lt;appender name="RollingFile" type="log4net.Appender.RollingFileAppender"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;file value="Log\\MeuArquivoDeLog.log"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;appendToFile value="true"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;datePattern value="yyyy-MM-dd"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;rollingStyle value="Composite"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;maximumFileSize value="1MB"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;maxSizeRollBackups value="10"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;layout type="log4net.Layout.PatternLayout"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;param name="ConversionPattern" value="%newline[%-5level]%newline%message%newline"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <!--layout&gt;&nbsp;&nbsp;&nbsp; <!--appender&gt;&nbsp;&nbsp;&nbsp; <!--<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:green;mso-ansi-language:EN-US" lang="EN-US">Mostra no Trace<span style="font-size:9.5pt;font-family:Consolas;
mso-bidi-font-family:Consolas;color:blue;mso-ansi-language:EN-US" lang="EN-US">-->&nbsp;&nbsp;&nbsp; &lt;appender name="A2" type="log4net.Appender.TraceAppender"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;layout type="log4net.Layout.PatternLayout"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <!--layout&gt;&nbsp;&nbsp;&nbsp; <!--appender&gt;&nbsp;&nbsp;&nbsp; &lt;root&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;level value="DEBUG" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;appender-ref ref="A2" /&gt;&nbsp;&nbsp;&nbsp; <!--root&gt;&nbsp;&nbsp;&nbsp; &lt;logger name="LogInFile"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;level value="Error"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;appender-ref ref="RollingFile"/&gt;&nbsp;&nbsp;&nbsp; <!--logger&gt;&nbsp;&nbsp;&nbsp; &lt;logger name="LogInEmail"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;level value="All"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;appender-ref ref="SmtpAppender"/&gt;&nbsp;&nbsp;&nbsp; <!--logger&gt;&nbsp; <!--log4net&gt;
Acima temos a configuração mista, ou seja, para salvar em arquivo, mostrar no trace e enviar email. Inicialmente o projeto estava chamando sempre para salvar em arquivo:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private log4net.ILog logger;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected void Page_Load(object sender, EventArgs e)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Vamos usar o logger LogInFile, que salva todos os tipos de erro&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logger = log4net.LogManager.GetLogger("LogInFile");&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;logger.Error("Lança a mensagem de error");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
No método GetLogger nos pedimos para usar a configuração para salvar em arquivo. Basta fazer a modificação para chamar a configuração do e-mail:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logger = log4net.LogManager.GetLogger("LogInEmail");&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;logger.Error("Lança a mensagem de error");
Uma boa idéia seria usar para enviar email somente quando acontecesse erros não tratados, para isso, basta colocar dentro do Global.asax no método Application_Error. 
Basta pegar a exceção lançada e passar a mensagem de erro para enviar:
private log4net.ILog logger;protected void Application_Error(object sender, EventArgs e)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Exception exc = Context.Error;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (exc is HttpUnhandledException)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; exc = Context.Error.InnerException;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; logger = log4net.LogManager.GetLogger("LogInEmail ");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;logger.Error(exc.Message);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
Agora o colocar esse tratamento de erro numa classe especializada, gerar uma DLL que possa ser usada em qualquer aplicação sua.