Pular para o conteúdo principal

Delphi Exception Logger

Olá pessoal, achei esta unit na internet, e resolvi fazer uma "cópia" do site onde ela estava hospedada.

Link original: http://www.jirihajek.net/delphi/ExceptLog.htm


A free exception logging for Delphi with additional information like source files, procedure names, line numbers, exception messages, etc.

(c) Jiri Hajek 2003-2005
E-mail:   jh   at   j i r i h a j e k   dot   net
Created for MediaMonkey, a free mp3 jukebox player and music library organizer

Purpose:
When you include this unit in your project, all exceptions that happens at run-time are automatically logged together with exception message, information about source of the exception and call stack content together with source files and line numbers information.

Environment:
This unit was tested under Delphi 7, it would probably work under other Delphi versions as well, but it might need some modifications in some magic constants in the code below.

Usage:

  1. Include this unit in your project.
  2. You'll also need an excellent leak detector for Delphi, MemCheck. It's also a single Delphi unit and so it isn't any proble to install it. (Exception Logger uses its methods to analyze call stack).
  3. Modify OutputFile constant below so that logs are written to a file you want.
  4. Recommended: Set your compiler options for debugging. It's a good idea to turn on "Project|Options|Linker|Include TD32 debug info" because then you get complete reports about source files, procedure names and line numbers. On the other hand, it makes your compiled exe file much bigger.
  5. Compile and run! You can distribute such compiled file even to your users and they can directly report any problem to you. Any exception that happens is written to the OutputFile as in the file below. It is also reported using OutputDebugString() method and so it can be trapped for example by Debug View application from System Internals.

License:
You can use this unit for any purpose, even commercial, as long as you leave this header here. Author cannot be blamed for any problem with this unit. If you don't agree, don't use it.

Download:
Download the unit ExceptLog.pas.
Obs.: Adicionei o codigo da unit logo abaix

Sample output:
This is a sample output after a single line
raise Exception.Create('Here!');
was added to OnFormCreate event of the main form of a project.

New exception:
Delphi exception, type Exception, message: Here!
Exception code: 250477278
Exception flags: 3
Number of parameters: 7
(no debug info) Find error: 7C81EB33
call stack - 0 : Module ELTestU.pas Routine @Eltestu@TForm1@FormCreate Line 27 Find error: 0045A7FA
call stack - 1 : Module Forms.pas Routine @Forms@TCustomForm@DoCreate Line 2648 Find error: 0044FEF3
call stack - 2 : Module Forms.pas Routine @Forms@TCustomForm@AfterConstruction Line 2575 Find error: 0044FB63
call stack - 3 :  Routine @System@@AfterConstruction Find error: 00403EDA
call stack - 4 : Module Forms.pas Routine @Forms@TApplication@CreateForm Line 6946 Find error: 00458DA7
call stack - 5 : Module ELTest.dpr Routine initialization Line 12 Find error: 0045EB64
call stack - 6 : (no debug info) Find error: 7C816D4B
call stack - 7 : (no debug info) Find error: FFFFFFFC


unit ExceptLog;

// Delphi Exception Logger
// http://www.jirihajek.net/delphi/ExceptLog.htm
// (c) Jiri Hajek 2003-2005
// E-mail: jh@jirihajek.net
// Created for MediaMonkey (http://www.mediamonkey.com), a free mp3 jukebox player and music library organizer

// Purpose: When you include this unit in your project, all exceptions that happens at run-time
// are automatically logged together with exception message, information about source of the
// exception and call stack content together with source files and line numbers information.

// Environment:
//  This unit was tested under Delphi 7, it would probably work under other Delphi versions
//  as well, but it might need some modifications in some magic constants in the code below.

// Usage:
//  1. Include this unit in your project
//  2. You'll also need an excellent leak detector for Delphi, MemCheck, from here:
//             http://v.mahon.free.fr/pro/freeware/memcheck/
//      (Exception Logger uses its methods to analyze callstack)
//  3. Modify OutputFile constant below so that logs are written to a file you want.
//  4. Recommended: Set your compiler options for debugging, this is described here:
//             http://v.mahon.free.fr/pro/freeware/memcheck/project_options.htm
//     It's a good idea to turn on "Project|Options|Linker|Include TD32 debug info"
//     because then you get complete reports about source files, procedure names and line numbers.
//     On the other hand, it makes your compiled exe file much bigger.
//  5. Compile and run! You can distribute such compiled file even to your users and they can
//     directly report any problem to you. Any exception that happens is written to the OutputFile
//     as specified below. It is also reported using OutputDebugString() method and so it can
//     be trapped for example by Debug View application from System Internals.

// License:
//   You can use this unit for any purpose, even commercial, as long as you leave this header here.
//   Author cannot be blamed for any problem with this unit. If you don't agree, don't use it.

interface

implementation

uses MemCheck, SysUtils, Windows;

const
  OutputFile = 'C:\Except.log';

type
  PExceptionRecord = ^TExceptionRecord;
  TExceptionRecord =
  record
    ExceptionCode        : LongWord;
    ExceptionFlags       : LongWord;
    OuterException       : PExceptionRecord;
    ExceptionAddress     : Pointer;
    NumberParameters     : Longint;
    case {IsOsException:} Boolean of
    True:  (ExceptionInformation : array [0..14] of Longint);
    False: (ExceptAddr: Pointer; ExceptObject: Pointer);
  end;

var
  oldRTLUnwindProc: procedure; stdcall;
  writeToFile : boolean = false;

procedure MyRtlUnwind; stdcall;
var
  PER : PExceptionRecord;

  procedure DoIt;
  var             // This is done in a sub-routine because string variable is used and we want it finalized
    s : string;
    E: Exception;
    CS: TCallStack;
    t : TextFile;
  begin
    s:='--------------------------------------------------------'#13#10;
    s:=s+'New exception:'#13#10;

    if PER^.ExceptionFlags and 1=1 then      // This seems to be an indication of internal Delphi exception,
    begin                                    // thus we can access 'Exception' class
      try
        E := Exception( PER^.ExceptObject);
        if (E is Exception) then
          s:=s+'Delphi exception, type '+E.ClassName+', message: '+E.Message+#13#10;
      except
      end;
    end;

    FillCallStack(CS, 5);    // 5 last entries seem to be unusable
    s:=s+        'Exception code: '+inttostr( PER^.ExceptionCode)+#13#10+
                 'Exception flags: '+inttostr( PER^.ExceptionFlags)+#13#10+
                 'Number of parameters: '+inttostr( PER^.NumberParameters)+#13#10+
                 TextualDebugInfoForAddress(Cardinal(PER^.ExceptionAddress))+#13#10+
                 CallStackTextualRepresentation(CS, '')+#13#10;

    OutputDebugString( PChar( s));

    if writeToFile then
    begin
      try
        Assign( t, OutputFile);
        Append( t);
        Writeln( t, s);
        Close( t);
      except
      end;
    end;
  end;
begin
  asm
    mov eax, dword ptr [EBP+8+13*4]         // magic numbers - works for Delphi 7
    mov PER, eax
  end;

  DoIt;
    
  asm
    mov esp, ebp
    pop ebp
    jmp oldRTLUnwindProc
  end;
end;

procedure InitExceptionLogging;
var
  f : file;
begin
  try
    Assign( f, OutputFile);
    Rewrite( f);
    Close( f);
    writeToFile := true;
  except
    writeToFile := false;
  end;
  oldRTLUnwindProc := RTLUnwindProc;
  RTLUnwindProc := @MyRtlUnwind;
end;

initialization
  InitExceptionLogging;
end.

Comentários

Postagens mais visitadas deste blog

Curso Fast Report - Aula 07 - Impressão de Etiquetas

Olá pessoal, bem vindos a mais uma aula de Fast Report. Desta vez iremos falar sobre impressão de etiquetas.  Primeiro iremos preparar nosso ambiente de dados. Geralmente eu uso uma tabela temporária (em memória ou ClientDataSet - qual você estiver acostumado a usar), pra poder preencher os dados das etiquetas, com uma estrutura simples: Texto1 - String - 100 Texto2 - String - 100 Texto3 - String - 100 Texto4 - String - 100 Texto5 - String - 100 Dessa forma, eu pego os dados de qualquer tabela e vou inserindo nessa tabela temporária. Assim eu consigo, por exemplo, imprimir várias cópias da mesma etiqueta, como por exemplo, quando é necessário etiquetar produtos, e existem várias peças de um mesmo produto. Veja um exemplo de produtos/estoque: Primeiro eu percorro a tabela, e vou inserindo um registro pra cada item. Se o item possui estoque maior que um 1 (por exemplo, estoque = 10), eu insiro 10 registros do mesmo item. Veja o código abaixo: procedure ... var i...

ACBR - Corrigir Erro Interno: 12175/12030/12029/12031

Erro Interno: 12175/12030/12029/12031 Atualização do Windows - Habilitar o TSL 1.2 ✔1.0) Instalar o Service Pack 1 (SP1) - Baixar em  https://www.microsoft.com/pt-BR/download/details.aspx?id=5842 ✔1.1) Responsável por atualização dos protocolos de SSL - Instalar KB2992611, https://www.catalog.update.microsoft.com/Search.aspx?q=2992611 ✔1.2) Responsável por HABILITAR o protocolo TLS 1.1 e 1.2. Instalar KB3140245  https://www.catalog.update.microsoft.com/search.aspx?q=kb3140245 ✔1.3) ou Baixar todas as atualizações disponíveis. Configuração do Protocolo no Internet Explorer Marque as opções Opções de Internet (no IE, menu Ferramentas, Opções de Internet) ✔ Não salvar páginas criptografadas em disco;  ✔ Usar SSL 3.0;   ✔ Usar TLS 1.0;   ✔ Usar TLS 1.2;  Desmarque as opções caso tenha ou estejam marcadas: ❌ Usar SSL 2.0;  ❌ Usar TLS 1.1; #Atualizações das Cadeias de Certificado ✔ https://www.gov.br/iti/pt-br/assuntos/navegadores Certificados por ...

Curso Fast Report - Aula 03 - Agrupamento de Dados e Totalizadores

Olá pessoal, estamos aqui mais uma vez com nosso curso de Fast Report. Hoje iremos ver como fazer o agrupamento dos dados, e fazer totalizadores, tanto por grupo como um totalizador geral. Vamos lá. Adicione uma nova query e outro frxDBDataSet ao form, e configure-os assim: Query Name : sqlReceber SQL : SELECT nome, numero, vencimento, valor, historico FROM receber ORDER BY vencimento frxDBDataSet Name : frxSqlReceber (nome usado pra referencias no Delphi) UserName : frxSqlReceber (nome usado pra referencias no FastReport) DataSet : sqlReceber Dê dois cliques no frxReport pra abrir o designer. Clique no botão Novo, vá ao menu Relatório, opção Dados e marque o frxSqlReceber. 2 cliques no MasterData e selecionar a fonte dos dados novamente. Remova a banda PageTitle e adicione a banda PageHeader . Adicione a banda GroupHeader e informe o field que será usado como agrupador. As opções dessa tela são: Manter grupo unido : não separa o cabeçal...