AS EMPRESAS ESTÃO "DESESPERADAS" POR ESTE TIPO DE PROFISSIONAL... - VOCÊ É UM DELES?

MEGA FORMAÇÃO EM INFRAESTRUTURA DE TI - O Conhecimento que Vira Dinheiro - CLIQUE AQUI

Você está em: PrincipalArtigosCsharp : Gravandoerroscomexception001
Quer receber novidades e e-books gratuitos?

Gravando Erros com Exception - Parte I

 

Usando arquivo de log.

 

Olá pessoal, meu nome é Mauricio Junior. Irei mostrar como gravar dentro de um arquivo de log, os erros gerados de dentro da sua aplicação. Nesse primeiro passo irei criar uma classe chamada AppException.cs com um método chamado LogErro.

 

Requisitos:

 

- Ferramenta Visual Studio.NET 2003 ou 2005;

- Conhecimento em escrita de arquivo;

- Conhecimento da linguagem C#.NET.

 

Criarei usando a IDE 2003 da Microsoft. (Referência 1.1 – Exception Parte I)

 

Referência: 1.1 – Exception Parte I

 

Criação da classe (Referência 1.2 – Exception Parte I)

 

Referência: 1.2 – Exception Parte I

 

A referência 1.2 apenas mostra a classe que gerei dentro da pasta WEB. No próximo passo é gerar o método que registra o log dentro do arquivo de erro.log. (Referência 1.3 – Exception Parte I)

 

public static void LogError(string message)
         {
              HttpContext context = HttpContext.Current;
              string filePath = context.Server.MapPath(System.Convert.ToString(System.Configuration.

ConfigurationSettings.AppSettings["ErrorLogFile"]));
              int gmtOffset = DateTime.Compare(DateTime.Now, DateTime.UtcNow);
              string gmtPrefix;
              if (gmtOffset > 0)
              {
                   gmtPrefix = "+";
              }
              else
              {
                   gmtPrefix = "";
              }
              string errorDateTime = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." +

DateTime.Now.Day.ToString() + " @ " + DateTime.Now.Hour.ToString() + ":" +

DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + " (GMT " + gmtPrefix +

gmtOffset.ToString() + ")";
              try
              {
                   System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true);
                   sw.WriteLine("## " + errorDateTime + " ## " + message + " ##");
                   sw.Close();
              }
              catch
              {
              }
         }

Referência: 1.4 – Exception Parte I

 

Explicação:

 

Começando com a assinatura do método.

 

 

public static void LogError(string message)



Referência: 1.5 – Exception Parte I

 

É um método publico e estático que não retorna valor algum e recebe um parâmetro de entrada do tipo string.

 

 

HttpContext context = HttpContext.Current;
              string filePath = context.Server.MapPath(System.Convert.ToString(System.Configuration.

ConfigurationSettings.AppSettings["ErrorLogFile"]));

 

Referência: 1.6 – Exception Parte I

 

A referência 1.6 apenas pego a configuração do arquivo que está descrito dentro do arquivo de configuração web.config. Mostrarei o mesmo mais pra frente.

 

 

int gmtOffset = DateTime.Compare(DateTime.Now, DateTime.UtcNow);
              string gmtPrefix;
              if (gmtOffset > 0)
              {
                   gmtPrefix = "+";
              }
              else
              {
                   gmtPrefix = "";
              }
              string errorDateTime = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + " @ " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + " (GMT " + gmtPrefix + gmtOffset.ToString() + ")";

 

Referência: 1.7 – Exception Parte I

 

A referência 1.7, configuro apenas as horas, data, segundo e minuto que irá ser gravado junto ao arquivo de configuração.

 

 

               try
              {
                   System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true);
                   sw.WriteLine("## " + errorDateTime + " ## " + message + " ##");
                   sw.Close();
              }
              catch
              {
              }

 

Referência: 1.8 – Exception Parte I

 

Essa última referência 1.8 apenas abre o arquivo e escreve os valores setados anteriormente dentro do arquivo e fecha.

 

Bom, fico por aqui.

 

No próximo passo mostrarei mais algumas configurações e métodos criados para utilização por completo.

 

Mauricio Junior

 

www.ascompras.com

www.aspneti.com

e-mail: mauricio@ascompras.com

 

Quer receber novidades e e-books gratuitos?

MEGA FORMAÇÃO EM INFRAESTRUTURA DE TI

(Online, Vitalício, Prático e Atualizado)!

  • Chega de ser Ignorado pelo Mercado!

  • A vida não vai Melhorar Sozinha!

  • Quem domina infraestrutura, domina o Mercado.

  • Com esta Formação você vai Dominar o Conhecimento e torne-se o Profissional que as Empresas estão Buscando, "desesperadamente", mas não estão encontrando.

NÃO PROCURE VAGAS, SEJA PROCURADO!

 

Curso Completo de Excel - Curso Online com Certificado - 925 Vídeo Aulas - 22 Cursos - 120:42 horas

 

Para Todos os Detalhes, Acesse:

Curso Completo de Excel - Curso Online com Certificado - 925 Vídeo Aulas - 22 Cursos - 120:42 horas

 

https://juliobattisti.com.br/curso-infra-ti.asp

 

Contato: Telefone: (51) 3717-3796 | E-mail: webmaster@juliobattisti.com.br | Whatsapp: (51) 99627-3434

Júlio Battisti Livros e Cursos Ltda | CNPJ: 08.916.484/0001-25 | Rua Vereador Ivo Cláudio Weigel, 537 - Universitário, Santa Cruz do Sul/RS, CEP: 96816-208

Todos os direitos reservados, Júlio Battisti 2001-2025 ®

LIVRO: MACROS E PROGRAMAÇÃO VBA NO EXCEL 2016 - CURSO COMPLETO E PRÁTICO

DOMINE A PROGRAMAÇÃO VBA NO EXCEL - 878 PÁGINAS - CLIQUE AQUI