Debian Codegraph @

examples/network/remote_logging/code/gameloghandler.pas

raw
1 {
2 Copyright 2020-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Log handler sending logs to server using asynchronous HTTP POST (TLogHandler). }
17 unit GameLogHandler;
18
19 interface
20
21 uses SysUtils, Math, Classes,
22 CastleWindow, CastleLog, CastleApplicationProperties, CastleKeysMouse,
23 CastleDownload, CastleClassUtils, CastleNotifications;
24
25 type
26 { Log handler sending logs to server using asynchronous HTTP POST. }
27 TLogHandler = class(TComponent)
28 strict private
29 InsideLogCallback: Boolean;
30 ProcessId: Cardinal;
31 procedure HttpPostFinish(const Sender: TCastleDownload; var FreeSender: Boolean);
32 public
33 constructor Create(AOwner: TComponent); override;
34 procedure LogCallback(const Message: String);
35 end;
36
37 var
38 { Set by UI state. }
39 LogNotifications: TCastleNotifications;
40
41 implementation
42
43 uses CastleUtils, CastleStringUtils;
44
45 constructor TLogHandler.Create(AOwner: TComponent);
46 begin
47 inherited;
48 { This "process id" is not used for any OS process management.
49 It's only a unique process id, hopefully unique across all current
50 application instances on all systems.
51 So we can just choose it using Random, no need to use Unix "pid" or
52 equivalent WinAPI function for this. }
53 ProcessId := Random(1000);
54 end;
55
56 procedure TLogHandler.LogCallback(const Message: String);
57
58 { Send, using HTTP post, one parameter. }
59 procedure HttpPost(const Url: String; const ParameterKey, ParameterValue: String);
60 var
61 Request: TCastleDownload;
62 begin
63 Request := TCastleDownload.Create(Application);
64 Request.Url := Url;
65 Request.HttpPostData.Values[ParameterKey] := ParameterValue;
66 Request.HttpMethod := hmPost;
67 Request.OnFinish := {$ifdef FPC}@{$endif} HttpPostFinish;
68 Request.Start;
69 end;
70
71 var
72 SendMessage: String;
73 begin
74 { Use InsideLogCallback to prevent from infinite recursion,
75 in case anything inside would also cause WritelnLog. }
76 if InsideLogCallback then Exit;
77
78 { Do not send messages about network communication, as they would cause infinite recursion too. }
79 if IsPrefix('Network:', Message) then
80 Exit;
81
82 InsideLogCallback := true;
83 try
84 try
85 // We use TrimRight to strip traling newline
86 SendMessage := ApplicationName + '[' + IntToStr(ProcessId) + '] ' + TrimRight(Message);
87 HttpPost('https://castle-engine.io/cge_logger.php', 'message', SendMessage);
88 except
89 { Catch exception, like
90 EInOutError: Could not initialize OpenSSL library
91 (easily possible on Linux with FPC < 3.3.1 due to libssl incompatibility).
92 Display it as nice warning, instead of crashing application. }
93 on E: Exception do
94 WritelnWarning('Sending log remotely failed: ' + ExceptMessage(E));
95 end;
96 finally InsideLogCallback := false end;
97 end;
98
99 procedure TLogHandler.HttpPostFinish(const Sender: TCastleDownload; var FreeSender: Boolean);
100 begin
101 { TCastleDownload does not guarantee that TCastleDownload.Contents
102 are set (not nil) when Status is dsError.
103 It depends on the protocol.
104 But we know that we use this only with http / https protocols, in which
105 case TCastleDownload.Contents are always set when finished, even on error. }
106 Assert(Sender.Contents <> nil);
107
108 if LogNotifications <> nil then
109 begin
110 case Sender.Status of
111 dsSuccess:
112 LogNotifications.Show(Format('SUCCESS: Posted log to "%s".' + NL +
113 'Server response (%d): %s', [
114 Sender.Url,
115 Sender.HttpResponseCode,
116 StreamToString(Sender.Contents)
117 ]));
118 dsError:
119 LogNotifications.Show(Format('ERROR: Cannot post log to "%s".' + NL +
120 'Error message: %s' + NL +
121 'Server response (%d): %s', [
122 Sender.Url,
123 Sender.ErrorMessage,
124 Sender.HttpResponseCode,
125 StreamToString(Sender.Contents)
126 ]));
127 else
128 raise EInternalError.Create('No other status is possible when request finished');
129 end;
130 end;
131 FreeSender := true;
132 end;
133
134 end.