读书人

怎么创建和读写LOG文件

发布时间: 2012-02-22 19:36:56 作者: rapoo

如何创建和读写LOG文件
我在一个应用程序中使用日志来记录程序运行中发生的异常等信息.想使用LOG文件做为日志文件.不需要如何创建和读写.

[解决办法]
其实就相当于操作.txt文件一样
你换下后缀不就行了?

[解决办法]
procedure LogToFile(astr: string; fn: string = 'AppLog ');
var
f: TextFile;
begin
astr := formatdatetime( 'yy/mm/dd HH:nn ', now) + ': '+ astr;
if fn = 'AppLog ' then
fn := ChangeFileExt(GetModuleName(HInstance), '. ' + formatdatetime( 'yymmdd ', now) + '.log.txt ');
AssignFile(f, fn);
try
if FileExists(fn) then
Append(f)
else Rewrite(f);
Writeln(f, astr);
{ insert code here that would require a Flush before closing the file }
Flush(f); { ensures that the text was actually written to file }
finally
CloseFile(f);
end;
end;

[解决办法]
http://www.delphifans.com/SoftView/SoftView_1065.html
看看这个例子吧,支持多线程
[解决办法]
以前的,
strLog:日志容;
modlevel:本模的跟;
sysloglevel:系跟;
(用版的sysloglevel就小,版的sysloglevel就大.modlevel就跟自已需要定)

procedure WriteLog(strLog:string;ModLevel,SysLogLevel:integer);
var
outFile:TextFile;
i:integer;
sLog:string[128];
acLog:array[0..159] of char;
sLogFile:string;
bNewFile:boolean;
begin
if ModLevel> SysLogLevel then exit;

for i:=ModLevel-1 downto 0 do begin //Indent
sLog:=Format( '%s%s ',[ ' ',sLog]);
end;

sLog:=FormatDateTime( 'YYYY-MM-DD HH:MM:SS:zzz ',Now)+#9+strLog;
if length(sLog)> 158 then sLog:=copy(sLog,1,158);
fillMemory(@acLog,160,ord( ' '));
for i:=0 to length(sLog)-1 do begin
acLog[i]:=sLog[i+1];
end;
sLogFile:= 'Log\SmartUp_ '+formatdatetime( 'MMDD ',Now)+ '.log ';
bNewFile:= FileExists(sLogFile);

AssignFile(outFile,sLogFile);
if Not bNewFile then ReWrite(outFile)
else Append(outFile);

WriteLn(outFile,acLog);
CloseFile(outFile);
end;
[解决办法]
TApplicationEvents 这个控件可以捕获所有错误,在additionial页上,捕获代码我日志就写在onexception 事件里就可以了!
[解决办法]
procedure TfrmMain.WriteLog(str: string);
var
F:textfile;
filename: string;
begin
if trim(str) <> ' ' then
try
filename := exepath+FormatDateTime( 'yyyy-mm-dd ',now)+ '.log ';
assignfile(f,filename);
if FileExists(filename) then reset(f) else rewrite(F);
append(f);
writeln(f,trim(str)+ '-> '+FormatDateTime( 'HH:MM:SS ',now));
flush(f);
finally
closefile(f);
end;
end;

读书人网 >.NET

热点推荐