Debian Codegraph @

src/base/castlelog.pas

raw
1 {
2 Copyright 2006-2022 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 { Logging. Log has to be activated in your program (nothing in the
17 Castle Game Engine activates it automatically) by InitializeLog. }
18 unit CastleLog;
19
20 {$include castleconf.inc}
21
22 {$ifndef PASDOC}
23 {$if (not defined(FPC)) and defined(MSWINDOWS) and defined(DEBUG)}
24 { Log using WinAPI OutputDebugString.
25 This is comfortably visible in Delphi IDE Event Log.
26 See https://stackoverflow.com/questions/11218434/how-to-view-output-of-outputdebugstring }
27 {$define CASTLE_LOG_TO_WINDOWS_EVENT_LOG}
28 {$endif}
29 {$endif}
30
31 interface
32
33 uses Classes;
34
35 { Is logging active. Initially no. Activate by InitializeLog.
36
37 @deprecated
38 Instead of checking "if Log then WritelnLog(...)",
39 *always* call WriteLnLog / WriteLnWarning,
40 this allows to collect logs even before InitializeLog may be called.
41 Even release applications usually have logging = on,
42 so it makes no sense to optimize for the "logging = off" case,
43 you need to make "logging = on" case always fast.
44
45 @exclude
46 }
47 function Log: boolean;
48 deprecated 'do not check is Log initialized';
49
50 type
51 { Prefix each log line with optional date/time. }
52 TLogTimePrefix = (
53 { No prefix. }
54 ltNone,
55 { Record a time for each log record. }
56 ltTime,
57 { Record date and time for each log record. }
58 ltDateTime
59 );
60
61 { Initialize logging.
62 See https://castle-engine.io/manual_log.php for more documentation about logging.
63
64 Where do we write the log:
65
66 @unorderedList(
67 @item(To the ALogStream, if you provide this parameter and it has non-nil value.)
68
69 @item(Otherwise, to the LogFileName, if you set this global variable to non-empty value.)
70
71 @item(Otherwise, we detect the best place to store the log automatically.
72 This detection depends on various factors -- the operating system,
73 whether the application is GUI/console (matters for Windows),
74 whether we are inside a shared library etc.
75 The exact algorithm is described on https://castle-engine.io/manual_log.php .
76
77 You can always check @link(LogOutput) value to see where the output is going now.
78 You can e.g. display @link(LogOutput) somewhere in UI.
79 )
80 )
81
82 In case of some platforms (Android and Nintendo Switch, now)
83 the log also @italic(always) goes to the device-specific log facility.
84 In case of Android, this is just "adb logcat", visible also if you run
85 "castle-engine run --target=android".
86 This is done regardless of the ALogStream or LogFileName values.
87
88 @param(ALogTimePrefix optionally adds date&time prefix to each log record.)
89 }
90 procedure InitializeLog(
91 const ALogStream: TStream = nil;
92 const ALogTimePrefix: TLogTimePrefix = ltNone); overload;
93
94 procedure InitializeLog(const ProgramVersion: string;
95 const ALogStream: TStream = nil;
96 const ALogTimePrefix: TLogTimePrefix = ltNone); overload;
97 deprecated 'to provide a Version to InitializeLog, set ApplicationProperties.Version earlier, instead of calling InitializeLog with an explicit ProgramVersion parameter';
98
99 { Log message. }
100 procedure WritelnLog(const Category: string; const Message: string); overload;
101 procedure WritelnLog(const Message: string); overload;
102
103 { Format and log a message.
104 This is a shortcut for @code(WritelnLog(Category, FormatDot(MessageBase, Args))). }
105 procedure WritelnLog(const Category: string; const MessageBase: string;
106 const Args: array of const); overload;
107 procedure WritelnLog(const MessageBase: string;
108 const Args: array of const); overload;
109
110 { Log message, without appending newline at the end (given Message
111 should already contain a final newline). }
112 procedure WriteLog(const Category: string; const Message: string); overload;
113 deprecated 'use WritelnLog, and do not add the final newline yourself to Message';
114
115 { Log multiline message.
116 The Message may, but doesn't have to, terminate with a newline --
117 we will format it OK either way. }
118 procedure WritelnLogMultiline(const Category: string; const Message: string);
119
120 procedure WriteLogMultiline(const Category: string; const Message: string); deprecated 'use WritelnLogMultiline';
121
122 { Log a warning, and call
123 @link(TCastleApplicationProperties.OnWarning ApplicationProperties.OnWarning)
124 event.
125
126 This outputs a log message.
127 We simply append the word "warning" to the Category, and pass arguments
128 to WritelnLog.
129
130 Then, @italic(regardless if the log is initialized or not),
131 we also call @link(TCastleApplicationProperties.OnWarning ApplicationProperties.OnWarning).
132 This allows to react to warnings e.g. by displaying a message dialog
133 (like @code(ShowMessage) in Lazarus, or @link(MessageOK) in CastleMessages,
134 or @link(TCastleWindow.MessageOK)).
135 Or by raising an exception, if you want to be strict about warnings. }
136 procedure WritelnWarning(const Category: string; const Message: string); overload;
137 procedure WritelnWarning(const Message: string); overload;
138
139 { A shortcut for @code(WritelnWarning(Category, FormatDot(MessageBase, Args))). }
140 procedure WritelnWarning(const Category: string; const MessageBase: string;
141 const Args: array of const); overload;
142 procedure WritelnWarning(const MessageBase: string;
143 const Args: array of const); overload;
144
145 var
146 { Dump backtrace (call stack) with each log.
147 Displaying line info requires compiling your program with -gl.
148 Note that displaying a backtrace may slow down logging considerably,
149 so use this only when you really need it, and disable for the final build. }
150 BacktraceOnLog: boolean = false;
151
152 { Current log date/time prefix style. Can be changed at runtime. }
153 LogTimePrefix: TLogTimePrefix;
154
155 { Set this to a filename that should contain log,
156 before calling @link(InitializeLog).
157 This may be an absolute or relative (to the current directory
158 at the time of InitializeLog call) path.
159 Note that this variable doesn't support URLs. It is only a simple filename.
160
161 It's your responsibility to choose a path that is writeable on current OS
162 (you can e.g. use GetAppConfigDir function from FPC RTL). }
163 LogFileName: String = '';
164
165 { Enable logging to StdOut, which is used on some platforms (like on Unix) and situations
166 (like when run under CGE editor or CGE build tool).
167 If @false, we will always log to some file. }
168 LogEnableStandardOutput: Boolean = true;
169
170 {$ifdef CASTLE_NINTENDO_SWITCH}
171 { Send a log message using platform-specific logging on NX.
172
173 You should always call WritelnLog instead of this,
174 unless you're possibly before memory manager was initialized,
175 or before unit's initialization took place.
176 }
177 procedure cgeNxLog(Message: PChar); cdecl; external 'cgeNxLog';
178 {$endif CASTLE_NINTENDO_SWITCH}
179
180 { Where is the log output going.
181 This is either a filename, or something special in brackets, like @code(<stdout>),
182 @code(<logging-not-initialized>),
183 @code(<custom-stream>). }
184 function LogOutput: String;
185
186 const
187 { How many last logs to preserve.
188 Last logs are useful to read using @link(LastLog),
189 observe in inspector (press F8 in debug build),
190 and they serve as a buffer in case you call InitializeLog
191 after something already did WritelnLog. }
192 MaxLastLogCount = 10;
193
194 function LastLogCount: Integer;
195 { Last log messages.
196 Use Index from 0 (newest) to LastLogCount - 1 (oldest). }
197 function LastLog(const Index: Integer): String;
198
199 implementation
200
201 uses {$ifdef CASTLE_LOG_TO_WINDOWS_EVENT_LOG} Windows, {$endif} SysUtils,
202 CastleUtils, CastleApplicationProperties, CastleClassUtils, CastleTimeUtils,
203 CastleStringUtils
204 {$ifdef ANDROID}, CastleAndroidInternalLog {$endif};
205
206 { On mobile platforms, do not place the log in GetAppConfigDir.
207 GetAppConfigDir may be '' and creating a subdirectory there may fail.
208 Although GetAppConfigDir is fixed in FPC trunk
209 (see too http://wiki.freepascal.org/Android )
210 but we still need to work with FPC 3.0.x.
211
212 ApplicationConfig has better logic for this,
213 using ApplicationConfigOverride, but it's set only from castlewindow_android.inc
214 once the activity starts. }
215 {$define CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG}
216 {$ifdef ANDROID} {$undef CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG} {$endif}
217 {$ifdef CASTLE_IOS} {$undef CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG} {$endif}
218
219 var
220 FLog: boolean = false;
221 FLogOutput: String;
222 LogStream: TStream;
223 LogStreamOwned: boolean;
224
225 FLastLog: array [0..MaxLastLogCount - 1] of String;
226 FLastLogCount: Integer;
227 // index of FLastLog entry containing first log message
228 FLastLogFirst: Integer;
229
230 procedure WriteLogCoreCore(const S: string); forward;
231
232 function Log: boolean;
233 begin
234 Result := FLog;
235 end;
236
237 procedure InitializeLog(const ProgramVersion: string;
238 const ALogStream: TStream;
239 const ALogTimePrefix: TLogTimePrefix);
240 begin
241 ApplicationProperties.Version := ProgramVersion;
242 InitializeLog(ALogStream, ALogTimePrefix);
243 end;
244
245 procedure InitializeLog(
246 const ALogStream: TStream;
247 const ALogTimePrefix: TLogTimePrefix);
248
249 function InitializeLogFile(const LogFileName: string): boolean;
250 begin
251 try
252 { without fmShareDenyNone, you cannot open the file while plugin runs }
253 LogStream := TFileStream.Create(LogFileName, fmCreate or fmShareDenyNone);
254 FLogOutput := LogFileName;
255 except
256 on E: EFCreateError do
257 begin
258 { Special message when LogFileName non-empty (usual case on Windows).
259 Merely warn when creating log file not possible.
260 Normal in many "production" cases when the directory of exe/plugin may not be writeable. }
261 WritelnWarning('Log', 'Cannot create log file "' + LogFileName + '"');
262 Exit(false);
263 end;
264 end;
265 LogStreamOwned := true;
266 Result := true;
267 end;
268
269 {$ifdef CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG}
270 { Similar to CastleFilesUtils.ApplicationConfig directory,
271 but returns a filename, and doesn't depend on CastleFilesUtils and friends. }
272 function ApplicationConfigPath: string;
273 begin
274 Result := InclPathDelim(GetAppConfigDir(false));
275 if not ForceDirectories(Result) then
276 raise Exception.CreateFmt('Cannot create directory for config file: "%s"',
277 [Result]);
278 end;
279 {$endif CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG}
280
281 var
282 WantsLogToStandardOutput: Boolean;
283 EnableStandardOutput: Boolean;
284 I: Integer;
285 begin
286 LogTimePrefix := ALogTimePrefix;
287
288 if FLog then Exit; { ignore 2nd call to InitializeLog }
289
290 LogStreamOwned := false;
291 FLogOutput := '';
292
293 WantsLogToStandardOutput := GetEnvironmentVariable('CASTLE_LOG') = 'stdout';
294 EnableStandardOutput := LogEnableStandardOutput and (not IsLibrary);
295
296 if ALogStream <> nil then
297 begin
298 LogStream := ALogStream;
299 FLogOutput := '<custom-stream>';
300 end
301 {$ifndef CASTLE_NINTENDO_SWITCH}
302 else
303 if WantsLogToStandardOutput and EnableStandardOutput and (StdOutStream <> nil) then
304 begin
305 { In this case, we know we have StdOutStream initialized OK,
306 even when IsConsole = false (because "castle-engine run"
307 and "castle-editor" are calling subprocesses to capture output
308 through pipes always).
309
310 We want to log to StdOutStream, to send them to "castle-editor"
311 output list. }
312 LogStream := StdOutStream;
313 FLogOutput := '<stdout>';
314 end else
315 { If not in CGE editor, then LogFileName takes precedence over everything else. }
316 if LogFileName <> '' then
317 begin
318 if not InitializeLogFile(LogFileName) then
319 Exit;
320 end else
321 { In a library (like Windows DLL) create log file in user's config directory.
322 Same thing for Windows GUI program.
323
324 Note: We should not write to
325 ChangeFileExt(ParamStr(0), '.log'))
326 Although it seems most natural on Windows when debugging,
327 it fails when the application is installed in a read-only directory under "Program Files" or such.
328
329 Note: We should never write to StdOutStream when IsConsole=false.
330 Although in some cases, GUI program may have an stdout
331 (when it is explicitly run like "xxx.exe > xxx.log"),
332 but we cannot rely on it. It's better to always write to file in case of IsConsole=false.
333 }
334 {$ifdef CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG}
335 if (not EnableStandardOutput) or (not IsConsole) then
336 begin
337 if not InitializeLogFile(ApplicationConfigPath + ApplicationName + '.log') then
338 Exit;
339 end else
340 {$endif CASTLE_USE_GETAPPCONFIGDIR_FOR_LOG}
341 begin
342 LogStream := StdOutStream;
343 FLogOutput := '<stdout>';
344 end
345 {$endif CASTLE_NINTENDO_SWITCH}
346 ;
347
348 { Note: on CASTLE_NINTENDO_SWITCH, it is possible to leave LogStream = nil.
349 It doesn't matter, we will log to cgeNxLog anyway. }
350
351 WriteLogCoreCore('Log for "' + ApplicationName + '".' + NL);
352 if ApplicationProperties.Version <> '' then
353 WriteLogCoreCore(' Version: ' + ApplicationProperties.Version + '.' + NL);
354 WriteLogCoreCore(' Started on ' + DateTimeToAtStr(CastleNow) + '.' + NL);
355 WriteLogCoreCore(' Castle Game Engine version: ' + CastleEngineVersion + '.' + NL);
356 WriteLogCoreCore(' Compiled with ' + SCompilerDescription + '.' + NL);
357 WriteLogCoreCore(' Platform: ' + SPlatformDescription + '.' + NL);
358
359 { Write to log output all pending messages, collected by LastLog. }
360 for I := LastLogCount - 1 downto 0 do
361 WriteLogCoreCore(LastLog(I));
362
363 { In case of exception in WriteStr in WriteLogCoreCore,
364 leave FLog as false.
365 This way following WritelnLog will not again cause the same exception. }
366 FLog := true;
367
368 if WantsLogToStandardOutput and EnableStandardOutput and (StdOutStream = nil) then
369 WritelnWarning('Cannot send logs through pipes. CASTLE_LOG=stdout defined but run as a GUI application. CASTLE_LOG=stdout should only be used internally, when running from the CGE editor or CGE build tool.');
370 end;
371
372 function LogOutput: String;
373 begin
374 if not FLog then
375 Result := '<logging-not-initialized>'
376 else
377 Result := FLogOutput;
378 end;
379
380 { Add the String to log contents.
381 Assumes that log is initialized.
382 Sends it to AndroidLog and LogStream and ApplicationProperties._Log. }
383 procedure WriteLogCoreCore(const S: string);
384 begin
385 // Assert(FLog); // do not check it, as InitializeLog uses it before FLog := true
386
387 ApplicationProperties._Log(S);
388
389 {$ifdef ANDROID}
390 AndroidLogRobust(alInfo, S);
391 {$endif}
392
393 {$ifdef CASTLE_LOG_TO_WINDOWS_EVENT_LOG}
394 OutputDebugString(PChar(S));
395 {$endif}
396
397 {$ifdef CASTLE_NINTENDO_SWITCH}
398 cgeNxLog(PChar(S));
399 {$else}
400 // we know that LogStream <> nil when FLog = true
401 WriteStr(LogStream, S);
402 {$endif CASTLE_NINTENDO_SWITCH}
403 end;
404
405 { Add the String to log contents.
406 - Optionally adds backtrace to the String.
407 - Adds the String to LastLog.
408 - If log initialized, sends it to AndroidLog and LogStream and ApplicationProperties._Log
409 }
410 procedure WriteLogCore(const S: string);
411 var
412 LogContents: String;
413 begin
414 LogContents := S;
415 {$ifdef FPC}
416 if BacktraceOnLog then
417 LogContents := LogContents + DumpStackToString(Get_Frame) + NL;
418 {$endif}
419
420 if FLog then
421 WriteLogCoreCore(LogContents);
422
423 if FLastLogFirst = 0 then
424 FLastLogFirst := MaxLastLogCount - 1
425 else
426 Dec(FLastLogFirst);
427 FLastLog[FLastLogFirst] := LogContents;
428 if FLastLogCount < MaxLastLogCount then
429 Inc(FLastLogCount);
430 //Assert(LastLog(0) = LogContents); // valid Assert, commented out only to not eat time even in DEBUG mode
431 end;
432
433 function LogTimePrefixStr: string;
434 begin
435 case LogTimePrefix of
436 ltNone: Result := '';
437 ltTime: Result := FormatDateTime('tt', CastleNow) + '> ';
438 ltDateTime: Result := FormatDateTime('yyyy"-"mm"-"dd" "tt', CastleNow) + '> ';
439 end;
440 end;
441
442 procedure WriteLog(const Category: string; const Message: string);
443 var
444 S: String;
445 begin
446 S := LogTimePrefixStr;
447 if Category <> '' then
448 S := S + Category + ': ';
449 S := S + Message;
450 WriteLogCore(S);
451 end;
452
453 procedure WritelnLog(const Category: string; const Message: string);
454 begin
455 // do not warn about using deprecated WriteLog here.
456 // In the future, WriteLog should be moved to the "implementation" section
457 // of the unit (internal), and undeprecated.
458 {$warnings off}
459 WriteLog(Category, Message + NL);
460 {$warnings on}
461 end;
462
463 procedure WritelnLog(const Message: string);
464 begin
465 WritelnLog('', Message);
466 end;
467
468 procedure WritelnLog(const Category: string; const MessageBase: string;
469 const Args: array of const);
470 begin
471 WritelnLog(Category, FormatDot(MessageBase, Args));
472 end;
473
474 procedure WritelnLog(const MessageBase: string;
475 const Args: array of const);
476 begin
477 WritelnLog('', FormatDot(MessageBase, Args));
478 end;
479
480 procedure WriteLogMultiline(const Category: string; const Message: string);
481 begin
482 WritelnLogMultiline(Category, Message);
483 end;
484
485 procedure WritelnLogMultiline(const Category: string; const Message: string);
486 begin
487 if LogTimePrefix <> ltNone then
488 WriteLogCore(LogTimePrefixStr + NL);
489 WriteLogCore(
490 '-------------------- ' + Category + ' begin' + NL +
491 // trim newlines at the end of Message
492 TrimEndingNewline(Message) + NL +
493 '-------------------- ' + Category + ' end' + NL)
494 end;
495
496 procedure WritelnWarning(const Category: string; const Message: string);
497 var
498 WarningCategory: String;
499 begin
500 if Category <> '' then
501 WarningCategory := 'Warning: ' + Category
502 else
503 WarningCategory := 'Warning';
504 WritelnLog(WarningCategory, Message);
505 ApplicationProperties._Warning(Category, Message);
506 end;
507
508 procedure WritelnWarning(const Message: string);
509 begin
510 WritelnWarning('', Message);
511 end;
512
513 procedure WritelnWarning(const Category: string; const MessageBase: string;
514 const Args: array of const);
515 begin
516 WritelnWarning(Category, FormatDot(MessageBase, Args));
517 end;
518
519 procedure WritelnWarning(const MessageBase: string;
520 const Args: array of const);
521 begin
522 WritelnWarning('', MessageBase, Args);
523 end;
524
525 function LastLogCount: Integer;
526 begin
527 Result := FLastLogCount;
528 end;
529
530 function LastLog(const Index: Integer): String;
531 begin
532 Assert(Between(Index, 0, FLastLogCount - 1));
533 Result := FLastLog[(FLastLogFirst + Index) mod MaxLastLogCount];
534 end;
535
536 initialization
537 finalization
538 if LogStreamOwned then
539 begin
540 FreeAndNil(LogStream);
541 FLog := false;
542 end;
543 end.