Naciśnij “Enter” aby skoczyć do treści

Tiny Radio Player #07 – Logowanie błędów

Do logowania błędów i wyjątków napiszemy niewielką klasę TLog. Jej zadaniem będzie odpowiednie sformatowanie i zapisanie informacji o błędzie. Błędy zapiszemy w pliku Application.log, który zostanie utworzony w głównym katalogu aplikacji.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
unit Log;
 
{$mode objfpc}{$H+}
 
interface
 
uses
  Classes, SysUtils, Consts
type
 
  TLog = class sealed (TObject)
  private
    class procedure SaveToFile(const Message: string);
  public
    class procedure LogException(const Message: string;
      const NameOfTheClass: string = EMPTY_STR;
      const NameOfTheMethod: string = EMPTY_STR;
      const E: Exception = nil); // A static method
  end;
 
implementation
 
uses
  Helpers;
 
class procedure TLog.LogException(const Message: string; const NameOfTheClass: string;
  const NameOfTheMethod: string; const E: Exception);
var
  exceptionMessage: string;
begin
  // Get exception message
  if E <> nil then
    exceptionMessage := E.Message
  else
    exceptionMessage := EMPTY_STR;
 
  // Save a message
  SaveToFile(
    Format('%s %s.%s:%s error raised, with message: %s',
      [DateTimeToStr(Now), NameOfTheClass, NameOfTheMethod, E.ClassName,
       Message + IIF(exceptionMessage <> EMPTY_STR, #13#10 + exceptionMessage, EMPTY_STR)]
    )
  );
end;
 
// Saves the message to the disk
class procedure TLog.SaveToFile(const Message: string);
var
  TF: TextFile;
  Path: string;
begin
  // path to the log file
  Path :=  ConcatPaths([GetApplicationPath, LOG_NAME]);
 
  AssignFile(TF, Path);
  try
    if FileExists(Path) then
      Append(TF)
    else
      Rewrite(TF);
 
    Writeln(TF, Message);
 
    Flush(TF);
 
  finally
    CloseFile(TF);
  end;
end;

Klasa TLog zawiera tylko jedną metodę publiczną LogException. Wymaga ona przekazania kilku parametrów takich jak nazwa klasy, nazwa metody, treści wyjątku oraz dodatkowej informacji opisującej wystąpienie błędu.

W razie wystąpienia błędu, logowanie może wyglądać mniej więcej tak

1
2
3
4
5
6
7
8
try
  // kod, który może zakończyć się błędem
except
  on E: Exception do
  begin
    LogException('Adding a new station to the database', ClassName, 'AddNewStation', E);
  end;
end;