danieleteti / loggerpro

An modern and pluggable logging framework for Delphi
Apache License 2.0
357 stars 91 forks source link

VCLMemoLogAppender enhancement - check for valid memo handle before sending a message #57

Closed Basti-Fantasti closed 2 years ago

Basti-Fantasti commented 2 years ago

I stumbled over a problem with the implementation of the logging class when I added a memo on my main panel as a log output option.

My logging class wrapper sends an ExitApplicationevent to the logger when the application terminates (in finalization part of my loggingclass wrapper)

At this point the form containing the memo is already destroyed so the FMemo.parent and FMemo.owner handles are already nil and lead to an error/exception when trying to write to the memo.

I've modified the WriteLog procedure to check if the owner of a TMemo is still valid before trying to write to it. In this way no exception is raised and the application can shut down sending the ExitApplication messages to the remaining LogAppenders like FileAppender or SyslogAppender

procedure TVCLMemoLogAppender.WriteLog(const aLogItem: TLogItem);
var
  lText: string;
begin
  if Assigned(FMemo) then
  begin
    if FMemo.owner = nil then exit;
  end;

  lText := Format(DEFAULT_LOG_FORMAT, [datetimetostr(aLogItem.TimeStamp), aLogItem.ThreadID, aLogItem.LogTypeAsString, aLogItem.LogMessage,
    aLogItem.LogTag]);
  TThread.Queue(nil,
    procedure
    begin
      FMemo.Lines.BeginUpdate;
      try
        if FMemo.Lines.Count = FMaxLogLines then
          FMemo.Lines.Delete(0);
        FMemo.Lines.Add(lText)
      finally
        FMemo.Lines.EndUpdate;
      end;
      SendMessage(FMemo.Handle, EM_SCROLLCARET, 0, 0);
    end);
end;
danieleteti commented 2 years ago

Thank you, merged