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.
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
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;
- Tiny Radio Player #01 – Wprowadzenie
- Tiny Radio Player #02 – Instalacja komponentów
- Tiny Radio Player #03 – Roboczy interfejs aplikacji
- Tiny Radio Player #04 – Budujemy silnik
- Tiny Radio Player #05 – Zapis ustawień aplikacji
- Tiny Radio Player #06 – Zmiana języka aplikacji
- Jesteś tu => Tiny Radio Player #07 – Logowanie błędów
- Tiny Radio Player #08 – Baza danych
- Tiny Radio Player #09 – Zarządzanie bazą SQLite
- Tiny Radio Player #10 – Lista stacji radiowych, konfiguracja VirtualTreeView
