procedure writeWorkLog(sqlstr: string);
var filev: TextFile;
ss: string;
begin
sqlstr:=DateTimeToStr(Now)+' Log: '+sqlstr;
ss:='c:\ErpRunLog.txt';
if FileExists(ss) then
begin
AssignFile(filev, ss);
append(filev);
writeln(filev, sqlstr);
end else begin
AssignFile(filev, ss);
ReWrite(filev);
writeln(filev, sqlstr);
end;
CloseFile(filev);
end;
unit WriteLog;
interface
uses SysUtils,windows, Classes,ExtCtrls,Forms;
type
TWriteLog = class
Private
logs:TstringList;
//定时器,每隔500ms自动保存一次。
FTmrSave:TTimer;
FAutoSave: Boolean;
FLogName: String;
FLogPath: String;
//定时器的事件。
procedure OnAutoSave(Sender:TObject);
procedure SetAutoSave(const Value: Boolean);
//定时修改Log文件名.每次保存之前要调用此函数
procedure SetLogName();
public
constructor Create;
//退出时要保存一次.
destructor Destroy; Override;
//添加要保存的log信息。自动附上时间。
procedure Addlog(sLog:string);
Published
//是否自动保存
property AutoSave:Boolean Read FAutoSave Write SetAutoSave;
//日志文件名.
property LogName :String Read FLogName Write FLogName;
Property LogPath :String Read FLogPath Write FLogPath;
end;
var
Gv_Log: TWriteLog;
implementation
procedure TWriteLog.SetLogName;
var
sPath,sDate:string;
begin
sDate:=FormatDateTime('yyyymmdd',Date);
if FLogPath <>'' then
sPath := FLogPath
else
sPath:=ExtractFilePath(Application.ExeName)+'LOG_PAY';
if not DirectoryExists(sPath) Then
CreateDir(sPath);
if Copy(sPath,Length(sPath),1)<>'\' then
sPath:=sPath+'\';
{//如果有重复的就改名。
i:=1;
if not FileExists(sPath+sDate+'.log') then
begin
fLogName:=sPath+sDate+'.Log';
end
else
begin
while fileExists(sPath+sDate+'--'+intToStr(i)+'.Log') do
inc(i);
fLogName:=sPath+sDate+'--'+intToStr(i)+'.Log';
end;
}
// 不检查是否有重名的文件。
FLogName:=sPath+sDate+'.Log';
end;
constructor TWriteLog.Create;
begin
Inherited;
FLogPath := '';
FTmrSave:=TTimer.Create(Nil);
FTmrSave.Interval:=500;
FTmrSave.OnTimer:=OnAutoSave;
//设置log文件名.
SetLogName;
logs:=TStringList.Create;
end;
destructor TWriteLog.Destroy;
begin
//保存
OnAutoSave(Nil);
FTmrSave.Free;
logs.Free;
Inherited;
end;
procedure TWriteLog.Addlog(sLog:string);
begin
logs.Add(DateTimeToStr(now)+Char(vk_Tab)+sLog);
//logs.Add(sLog);
if not FTmrSave.Enabled Then
FTmrSave.Enabled:=True;
end;
procedure TWriteLog.OnAutoSave(Sender: TObject);
var
F: TFileStream;
begin
FTmrSave.Enabled:=false;
if Logs.Count>0 Then
begin
SetLogName;
if FileExists(fLogName) then
begin
F:=TFileStream.Create(fLogName,fmOpenWrite);
end
else begin
F:=TFileStream.Create(fLogName,fmCreate,fmShareExclusive);
end;
F.Seek(0,soFromEnd);
Logs.SaveToStream(F);
F.Free;
Logs.Clear;
FTmrSave.Enabled:=true;
end;
end;
procedure TWriteLog.SetAutoSave(const Value: Boolean);
begin
FAutoSave := Value;
Self.FTmrSave.Enabled := Value;
end;
end.