-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathLog.pas
More file actions
423 lines (385 loc) · 13.3 KB
/
Log.pas
File metadata and controls
423 lines (385 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
unit Log;
////////////////////////////////////////////////////////////////////////////////
//
// Author: Jaap Baak
// https://github.com/transportmodelling/Utils
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface
////////////////////////////////////////////////////////////////////////////////
Uses
SysUtils, Classes, Windows, Math, IOUtils, DateUtils, Parse;
Type
TRunTime = Type UInt64; // Run time in milliseconds
TRunTimeHelper = record helper for TRunTime
public
Constructor Create(const StartTime,StopTime: TDateTime);
Procedure SetValue(const StartTime,StopTime: TDateTime);
Function ToString: String;
end;
TLogEvent = Procedure(Sender: TObject; const Line: String) of Object;
TLogFile = Class
private
Type
TFileInfo = record
FileLabel,FileInfo: String;
end;
Const
MaxPathLevels = 4;
Var
LogFileInfo: Boolean;
Buffer,SeparatorLine: String;
LogEvent: TLogEvent;
StartTime: TDateTime;
Console: Boolean;
ConsoleWidth: Integer;
LogStream: TFileStream;
LogWriter: TStreamWriter;
InputFiles,OutputFiles: array of TFileInfo;
Procedure OnAppend(Sender: TObject);
Function ShortenPath(const Path: string): string;
Function FileProperties(const FileName: string): string;
Function FileInfo(const FileName: string; NameOnly: Boolean): string;
Function VarRecToStr(VarRec: TVarRec; NDecimals: Integer): String;
public
Constructor Create(const OnLog: TLogEvent = nil); overload;
Constructor Create(const LogFileName: String;
const Separator: Char;
const SeparatorCount: Integer;
const Echo: Boolean = false;
const OnLog: TLogEvent = nil); overload;
Constructor Create(const LogFileName: String;
const Echo: Boolean = false;
const Append: Boolean = false;
const OnAppend: TNotifyEvent = nil;
const OnLog: TLogEvent = nil); overload;
Procedure Log(const Line: String = ''; const LineFeed: Boolean = true); overload;
Procedure Log(const Line: String; const Width: Integer; const LineFeed: Boolean = true); overload;
Procedure Log(const Columns: array of String; const ColumnWidths: Integer); overload;
Procedure Log(const Columns: array of String; const ColumnWidths: array of Integer); overload;
Procedure Log(const Columns: array of const; const ColumnWidths, NDecimals: Integer); overload;
Procedure Log(const Columns: array of const; const ColumnWidths: array of Integer; const NDecimals: Integer); overload;
Procedure Log(const Columns: array of const; const ColumnWidths,NDecimals: array of Integer); overload;
Procedure Log(const Error: Exception); overload;
Procedure Log(const FileLabel,FileName: String); overload;
Procedure LogFileContent(const FileName: String);
Procedure SetLogFileInfo(LogInfo: Boolean);
Procedure InputFile(const FileLabel,FileName: String);
Procedure OutputFile(const FileLabel,FileName: String);
Procedure Flush;
Destructor Destroy; override;
public
end;
Var
LogFile: TLogFile = nil;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
Constructor TRunTimeHelper.Create(const StartTime,StopTime: TDateTime);
begin
SetValue(StartTime,StopTime);
end;
Procedure TRunTimeHelper.SetValue(const StartTime,StopTime: TDateTime);
begin
Self := MilliSecondsBetween(StartTime,StopTime);
end;
Function TRunTimeHelper.ToString: String;
const
MillisPerDay = Int64(MSecsPerSec*SecsPerMin*MinsPerHour*HoursPerDay);
MillisPerHour = Int64(MSecsPerSec*SecsPerMin*MinsPerHour);
MillisPerminute = Int64(MSecsPerSec*SecsPerMin);
begin
var RunTime := Self;
// Days
var Days := RunTime div MillisPerDay;
if Days > 0 then
if Days >= 10 then
Result := Days.ToString + ':'
else
Result := '0' + Days.ToString + ':'
else
Result := '';
RunTime := RunTime mod MillisPerDay;
// Hours
var Hours := RunTime div MillisPerHour;
if Hours >= 10 then
Result := Result + Hours.ToString + ':'
else
Result := Result + '0' + Hours.ToString + ':';
RunTime := RunTime mod MillisPerHour;
// Minutes
var Minutes := RunTime div MillisPerminute;
if Minutes >= 10 then
Result := Result + Minutes.ToString + ':'
else
Result := Result + '0' + Minutes.ToString + ':';
RunTime := RunTime mod MillisPerminute;
// Seconds
var Seconds := RunTime div MSecsPerSec;
if Seconds >= 10 then
Result := Result + Seconds.ToString
else
Result := Result + '0' + Seconds.ToString;
end;
////////////////////////////////////////////////////////////////////////////////
Constructor TLogFile.Create(const OnLog: TLogEvent = nil);
var
CBI: TConsoleScreenBufferInfo;
begin
SetLogFileInfo(true);
LogEvent := OnLog;
Console := IsConsole;
if Console then
begin
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),CBI);
ConsoleWidth := CBI.dwSize.X;
end;
StartTime := Now;
Log('START ' + DateTimeToStr(StartTime));
Log('Executable: ' + FileInfo(ParamStr(0),true));
Log('Computer: ' + GetEnvironmentVariable('COMPUTERNAME'));
end;
Constructor TLogFile.Create(const LogFileName: String;
const Separator: Char;
const SeparatorCount: Integer;
const Echo: Boolean = false;
const OnLog: TLogEvent = nil);
// On appending a separator line is written to the log file
begin
SeparatorLine := StringOfChar(Separator,SeparatorCount);
Create(LogFileName,Echo,true,OnAppend,OnLog);
end;
Constructor TLogFile.Create(const LogFileName: String;
const Echo: Boolean = false;
const Append: Boolean = false;
const OnAppend: TNotifyEvent = nil;
const OnLog: TLogEvent = nil);
var
CBI: TConsoleScreenBufferInfo;
begin
inherited Create;
SetLogFileInfo(true);
LogEvent := OnLog;
// Get console witdth
Console := IsConsole and Echo;
if Console then
begin
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),CBI);
ConsoleWidth := CBI.dwSize.X;
end;
// Open file
if FileExists(LogFileName) and Append then
begin
LogStream := TFileStream.Create(LogFileName,fmOpenWrite or fmShareDenyWrite);
LogStream.Seek(0,soEnd);
LogWriter := TStreamWriter.Create(LogStream,TEncoding.ASCII,4096);
if Assigned(OnAppend) then OnAppend(Self);
end else
begin
LogStream := TFileStream.Create(LogFileName,fmCreate or fmShareDenyWrite);
LogWriter := TStreamWriter.Create(LogStream,TEncoding.ASCII,4096);
end;
LogWriter.AutoFlush := false;
// Log start info
StartTime := Now;
Log('START ' + DateTimeToStr(StartTime));
Log('Executable: ' + FileInfo(ParamStr(0),true));
Log('Computer: ' + GetEnvironmentVariable('COMPUTERNAME'));
end;
Procedure TLogFile.OnAppend(Sender: TObject);
begin
Log;
Log(SeparatorLine);
Log;
end;
Function TLogFile.ShortenPath(const Path: string): string;
Var
Parser: TStringParser;
begin
var RootPath := TPath.GetPathRoot(Path);
Parser.SetSeparators([PathDelim]);
Parser.ExcludeEmpty := false;
Parser.Assign(Copy(Path,Length(RootPath)+1,MaxInt));
if Parser.Count <= MaxPathLevels+1 then
Result := Path
else
begin
Result := RootPath + '...';
for var Level := MaxPathLevels downto 1 do
Result := Result + PathDelim + Parser[Parser.Count-Level];
end;
end;
Function TlogFile.FileProperties(const FileName: string): string;
begin
Result := DateTimeToStr(TFile.GetLastWriteTime(FileName)) + '; ' +
TFile.GetSize(FileName).ToString + ' bytes';
end;
Function TLogFile.FileInfo(const FileName: string; NameOnly: Boolean): string;
begin
if NameOnly then
Result := ExtractFileName(FileName)
else
Result := ShortenPath(FileName);
Result := Result + '; ' + FileProperties(FileName);
end;
Function TLogFile.VarRecToStr(VarRec: TVarRec; NDecimals: Integer): String;
begin
case VarRec.VType of
vtInteger: Result := VarRec.VInteger.ToString;
vtInt64: Result := VarRec.VInt64^.ToString;
vtChar: Result := VarRec.VChar;
vtExtended: Result := FloatToStrF(VarRec.vExtended^,ffFixed,15,NDecimals);
vtString: Result := VarRec.VString^;
vtUnicodeString: Result := String(VarRec.VUnicodeString);
vtPChar: Result := VarRec.VPChar;
vtAnsiString: Result := String(VarRec.VAnsiString);
vtCurrency: Result := VarRec.VCurrency^.ToString;
vtVariant: Result := String(VarRec.VVariant^);
else raise Exception.Create('Unsupported type in Log');
end;
end;
Procedure TLogFile.Log(const Line: String = ''; const LineFeed: Boolean = true);
begin
Buffer := Buffer + Line;
if LineFeed then
begin
// Write to consol
if Console then
if Buffer.Length <= ConsoleWidth then
writeln(Buffer)
else
write(Copy(Buffer,1,ConsoleWidth));
// Write to file
if LogWriter <> nil then LogWriter.WriteLine(Buffer);
// Fire log event
if Assigned(LogEvent) then TThread.Synchronize(nil,Procedure
begin
LogEvent(Self,Buffer)
end);
// Reset buffer
Buffer := '';
end;
end;
Procedure TLogFile.Log(const Line: String; const Width: Integer; const LineFeed: Boolean = true);
begin
for var Space := Line.Length+1 to Width do Buffer := Buffer + ' ';
Log(Line,LineFeed);
end;
Procedure TLogFile.Log(const Columns: array of String; const ColumnWidths:Integer);
begin
for var Column := low(Columns) to high(Columns) do Log(Columns[Column],ColumnWidths,false);
Log;
end;
Procedure TLogFile.Log(const Columns: array of String; const ColumnWidths: array of Integer);
begin
if Length(Columns) = Length(ColumnWidths) then
begin
for var Column := low(Columns) to high(Columns) do Log(Columns[Column],ColumnWidths[Column],false);
Log;
end else
raise Exception.Create('Inconsistent method arguments');
end;
Procedure TLogFile.Log(const Columns: array of Const; const ColumnWidths, NDecimals: Integer);
Var
StringColumns: array of String;
begin
SetLength(StringColumns,Length(Columns));
for var Column := low(Columns) to high(Columns) do StringColumns[Column] := VarRecToStr(Columns[Column],NDecimals);
Log(StringColumns,ColumnWidths);
end;
Procedure TLogFile.Log(const Columns: array of Const; const ColumnWidths: array of Integer; const NDecimals: Integer);
Var
StringColumns: array of String;
begin
SetLength(StringColumns,Length(Columns));
for var Column := low(Columns) to high(Columns) do StringColumns[Column] := VarRecToStr(Columns[Column],NDecimals);
Log(StringColumns,ColumnWidths);
end;
Procedure TLogFile.Log(const Columns: array of Const; const ColumnWidths,NDecimals: array of Integer);
Var
StringColumns: array of String;
begin
SetLength(StringColumns,Length(Columns));
for var Column := low(Columns) to high(Columns) do StringColumns[Column] := VarRecToStr(Columns[Column],NDecimals[column]);
Log(StringColumns,ColumnWidths);
end;
Procedure TLogFile.Log(const Error: Exception);
begin
Log('ERROR: ' + Error.Message);
end;
Procedure TLogFile.Log(const FileLabel,FileName: String);
begin
Log(FileLabel + ': ' + FileInfo(FileName,false));
end;
Procedure TLogFile.LogFileContent(const FileName: String);
begin
var Reader := TStreamReader.Create(FileName);
try
while not Reader.EndOfStream do Log(Reader.ReadLine);
finally
Reader.Free;
end;
end;
Procedure TLogFile.SetLogFileInfo(LogInfo: Boolean);
begin
LogFileInfo := LogInfo;
end;
Procedure TLogFile.InputFile(const FileLabel,FileName: String);
Var
InputFile: TFileInfo;
begin
if LogFileInfo then
begin
InputFile.FileLabel := FileLabel;
InputFile.FileInfo := FileInfo(FileName,false);
InputFiles := InputFiles + [InputFile];
end;
end;
Procedure TLogFile.OutputFile(const FileLabel,FileName: String);
Var
OutputFile: TFileInfo;
begin
if LogFileInfo then
begin
OutputFile.FileLabel := FileLabel;
OutputFile.FileInfo := FileName;
OutputFiles := OutputFiles + [OutputFile];
end;
end;
Procedure TLogFile.Flush;
begin
LogWriter.Flush;
end;
Destructor TLogFile.Destroy;
begin
// Log buffered content
if Buffer <> '' then Log;
// Log input files
if Length(InputFiles) > 0 then
begin
Log;
Log('Input files:');
for var InpFile := low(InputFiles) to high(InputFiles) do
Log(InputFiles[InpFile].FileLabel + ': ' + InputFiles[InpFile].FileInfo);
end;
// Log output files
if Length(OutputFiles) > 0 then
begin
Log;
Log('Output files:');
for var OutpFile := low(OutputFiles) to high(OutputFiles) do
if FileExists(OutputFiles[OutpFile].FileInfo) then
Log(OutputFiles[OutpFile].FileLabel + ': ' + FileInfo(OutputFiles[OutpFile].FileInfo,false));
end;
// Log stop time
var StopTime := Now;
var RunTime := TRunTime.Create(StartTime,StopTime);
Log;
Log('STOP ' + DateTimeToStr(StopTime) + ' (Run time: ' + RunTime.ToString+ ')');
// Destroy objects
LogWriter.Free;
LogStream.Free;
inherited Destroy;
end;
end.