Print debugging statement: Difference between revisions

Content added Content deleted
No edit summary
Line 148: Line 148:
[debug.d@17] Goodbye world!
[debug.d@17] Goodbye world!
[debug.d@18] Goodbye world!</pre>
[debug.d@18] Goodbye world!</pre>
=={{header|Delphi}}==
{{libheader| winapi.windows}}
{{libheader| System.sysutils}}
Delphi has a "OutputDebugString" for debug, but not give lines and filename of source.
<lang Delphi>
program DebugApp;


{$APPTYPE CONSOLE}

uses
winapi.windows,
System.sysutils;

function Add(x, y: Integer): Integer;
begin
Result := x + y;
OutputDebugString(PChar(format('%d + %d = %d', [x, y, result])));
end;

begin
writeln(Add(2, 7));
readln;
end.</lang>

In next we have a workaround using a idea from '''user3989283'''[[https://stackoverflow.com/questions/7214213/how-to-get-line-number-at-runtime]]. This code override the default assert function to gain access to line and file name.
Obs.: In this example default action of assert is disabled, but you can enable calling in HookAssert (at end).

<lang Delphi>
program DebugApp;

{$APPTYPE CONSOLE}

uses
winapi.windows,
System.sysutils,
System.ioutils;

var
OldAssert: TAssertErrorProc;

procedure HookAssert(const M, F: string; L: Integer; E: Pointer);
var
msg: string;
fFile: Text;
const
LOG_FILE = '.\Debug.log';
begin
msg := '[' + DateTimeToStr(now) + ']';
msg := msg + format(' [Line: %.4d] File: %s', [L, F]);

Assign(fFile, LOG_FILE);
if FileExists(LOG_FILE) then
Append(fFile)
else
Rewrite(fFile);
Write(fFile, msg + #10);
Write(fFile, M + #10);
Close(fFile);
// Uncomment next line to enable the original assert function
// OldAssert(M, F, L, E);
end;

procedure AttachDebug;
begin
OldAssert := AssertErrorProc;
AssertErrorProc := HookAssert;
end;

procedure ReleaseDebug;
begin
AssertErrorProc := OldAssert;
end;

function Add(x, y: Integer): Integer;
begin
Result := x + y;
Assert(false, (format('%d + %d = %d', [x, y, result])));
end;

begin
AttachDebug;

writeln(Add(2, 7));

ReleaseDebug;
end.</lang>
{{out}}
Example log:
<pre>
[26/08/2020 18:56:51] [Line: 0051] File: ...\Debug\DebugApp.dpr
2 + 7 = 9
</pre>
=={{header|Go}}==
=={{header|Go}}==
Go doesn't have a built-in print debugging statement as such. Nor does it have macros.
Go doesn't have a built-in print debugging statement as such. Nor does it have macros.