Repository navigation
Expand file tree
/
Copy pathuGetItSessionLog.pas
More file actions
82 lines (71 loc) · 2.2 KB
/
Copy pathuGetItSessionLog.pas
File metadata and controls
82 lines (71 loc) · 2.2 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
unit uGetItSessionLog;
interface
uses
System.Classes;
type
TLogOrigin = (loGui, loGetItCmd);
TGetItSessionLog = class
strict private
class var FWriter: TStreamWriter;
class var FFileName: string;
class destructor Destroy;
public
class procedure StartSession(const Directory: string = ''); static;
class function Append(const Text: string; const Origin: TLogOrigin): string; static;
class procedure OpenFolder; static;
class property FileName: string read FFileName;
end;
implementation
uses
Winapi.Windows, Winapi.ShlObj, Winapi.ShellAPI,
System.SysUtils, System.IOUtils;
class procedure TGetItSessionLog.StartSession(const Directory: string);
var
Folder: array[0..MAX_PATH] of Char;
Id: TGUID;
Stream: TFileStream;
begin
if Directory = '' then
begin
if SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, SHGFP_TYPE_CURRENT, Folder) <> S_OK then
raise EInOutError.Create('Cannot locate the local application data folder for logs.');
FFileName := TPath.Combine(string(Folder), 'GetItcmdGUI\Logs');
end
else
FFileName := Directory;
TDirectory.CreateDirectory(FFileName);
CreateGUID(Id);
FFileName := TPath.Combine(FFileName, FormatDateTime('yyyy-mm-dd_hh-nn-ss', Now) +
'_' + GUIDToString(Id) + '.log');
Stream := TFileStream.Create(FFileName, fmCreate or fmShareDenyWrite);
try
FWriter := TStreamWriter.Create(Stream, TEncoding.UTF8);
FWriter.OwnStream;
Stream := nil;
finally
Stream.Free;
end;
FWriter.AutoFlush := True;
end;
class destructor TGetItSessionLog.Destroy;
begin
FWriter.Free;
end;
class function TGetItSessionLog.Append(const Text: string; const Origin: TLogOrigin): string;
const
OriginNames: array[TLogOrigin] of string = ('GUI', 'GetItCmd');
begin
Result := Format('[%s] [%s] %s',
[FormatDateTime('hh:nn:ss.zzz', Now), OriginNames[Origin], Text]);
FWriter.WriteLine(Result);
end;
class procedure TGetItSessionLog.OpenFolder;
var
Code: NativeInt;
begin
Code := ShellExecute(0, 'open', PChar(ExtractFilePath(FFileName)), nil, nil, SW_SHOWNORMAL);
if Code <= 32 then
raise EInOutError.CreateFmt('Cannot open log folder (ShellExecute code %d): %s',
[Code, ExtractFilePath(FFileName)]);
end;
end.