procedure TLogger.WriteLog(Log: String; const Args: array of const; const LogLevel: Integer = 0);
begin
WriteLog(Format(Log, Args), LogLevel);
end;
procedure TLogger.WriteLog(Log: String; const LogLevel: Integer = 0);
var
logName: String;
fMode: Word;
bytes: TBytes;
begin
EnterCriticalSection(FCSLock);
try
if not Enabled then
Exit;
ShowLog(Log, LogLevel); // 显示日志到容器
if LogLevel >= WRITE_LOG_MIN_LEVEL then
begin
logName := FormatDateTime('yyyymmdd', Now) + '.log';
if FLogName <> logName then
begin
FLogName := logName;
if FileExists(FLogFileDir + FLogName) then // 如果当天的日志文件存在
fMode := fmOpenWrite or fmShareDenyNone
else
fMode := fmCreate or fmShareDenyNone;
if Assigned(FFileStream) then
FreeAndNil(FFileStream);
FFileStream := TFileStream.Create(FLogFileDir + FLogName, fMode);
end;
procedure TLogger.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
end;
procedure TLogger.SetLogFileDir(const Value: string);
begin
FLogFileDir := Value;
if not DirectoryExists(FLogFileDir) then
if not ForceDirectories(FLogFileDir) then
begin
raise Exception.Create('日志路径错误,日志类对象不能被创建');
end;
end;
procedure TLogger.SetLogShower(const Value: TComponent);
begin
FLogShower := Value;
end;
procedure TLogger.ShowLog(Log: String; const LogLevel: Integer = 0);
var
lineCount: Integer;
listItem: TListItem;
begin
if FLogShower = nil then
Exit;
if (FLogShower is TMemo) then
begin
if SHOW_LOG_ADD_TIME then
Log := FormatDateTime(SHOW_LOG_TIME_FORMAT, Now) + ' ' + Log;
lineCount := TMemo(FLogShower).Lines.Add(Log);
// 滚屏到最后一行
SendMessage(TMemo(FLogShower).Handle, WM_VSCROLL, SB_LINEDOWN, 0);
if lineCount >= SHOW_LOG_CLEAR_COUNT then
TMemo(FLogShower).Clear;
end
else if (FLogShower is TListBox) then
begin
if SHOW_LOG_ADD_TIME then
Log := FormatDateTime(SHOW_LOG_TIME_FORMAT, Now) + ' ' + Log;
lineCount := TListBox(FLogShower).Items.Add(Log);
SendMessage(TListBox(FLogShower).Handle, WM_VSCROLL, SB_LINEDOWN, 0);
if lineCount >= SHOW_LOG_CLEAR_COUNT then
TListBox(FLogShower).Clear;
end
else if (FLogShower is TListView) then
begin
listItem := TListView(FLogShower).Items.Add;
if SHOW_LOG_ADD_TIME then
listItem.Caption := FormatDateTime(SHOW_LOG_TIME_FORMAT, Now);
if Assigned(TListView(FLogShower).SmallImages) and (TListView(FLogShower).SmallImages.Count - 1 >= LogLevel) then
listItem.ImageIndex := LogLevel; // 可以根据不同等级显示不同图片
listItem.SubItems.Add(Log);
SendMessage(TListView(FLogShower).Handle, WM_VSCROLL, SB_LINEDOWN, 0);
if TListView(FLogShower).Items.Count >= SHOW_LOG_CLEAR_COUNT then
TListView(FLogShower).Items.Clear;
end
else
raise Exception.Create('日志容器类型不支持:' + FLogShower.ClassName);
end;
destructor TLogger.Destroy;
begin
DeleteCriticalSection(FCSLock);
if Assigned(FFileStream) then
FreeAndNil(FFileStream);