フォーラム


ゲスト  

ようこそ ゲスト さん。このフォーラムに投稿するには 登録が必要です。

ページ: [1]
トピック: リリースアプリケーション用デバッグ風ログの作成方法
tetupei
メンバー
投稿数: 1
リリースアプリケーション用デバッグ風ログの作成方法
on: 2013/12/18 11:33 Wed

開発をしていると、内部処理を順を追ってトレースすることがよくあります。
デバッグ時は、ブレークポイントを設定したり、OutputDebugString();を使用しますが、
これらは、リリース後のユーザーがプロセスを確認することはできません。
リリース後もすべての関数から状況を表示させるようなLog表示の簡単な例です。
今回は、Form1のListBox1をログ通知ウィンドウとし、サンプルクラスTTestClassの内部関数をログ出力させています。
実装には全てのクラスファイルのusesに追加できるよう、新規ユニットを用います。
昔、これの実装方法がわからずとんでもなく複雑なプログラムを作った経緯があるため、ここに掲載させていただきます。

//UUserLog.pas:ログ作成用ファイル
unit UUserLog;

interface

procedure Log(aStr:string);

type
TLogEvent = procedure(aStr: string) of object;
var
Log_Event:TLogEvent;

implementation

procedure Log(aStr: string);
begin
if Assigned(Log_Event) then
Log_Event(aStr);
end;

end.

 

//UnitTest.pas:内部処理にログ出力させるサンプルクラス
unit UnitTest;

interface

uses
System.SysUtils,
UUserLog; //Logを使いたいユニットのusesにUUserLogを追加

type
//他のクラスからUUserLogに書き込むテストクラス
TTestClass = class(TObject)
public
function Addition(a,b:Integer):Integer;
end;

implementation

{ TTestClass }

function TTestClass.Addition(a, b: Integer): Integer;
begin
//Log出力したい場所にLog()を挿入するだけ
Log(Format('TTestClass.Addition:%d+%d=%d',[a,b,a+b]));
Result := a + b;
end;

end.

 

//Unit1.pas:実際にログを表示させるフォーム
unit Unit1;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
UnitTest, UUserLog; //Logを使いたいユニットのusesにUUserLogを追加

type
TForm1 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private 宣言 }
procedure UserLog(aStr: string);
public
{ Public 宣言 }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
i:Integer;
aTest : TTestClass; //他のクラスからUUserLogに書き込むテストクラス
begin
aTest := TTestClass.Create;
i := aTest.Addition(5,3); //関数内部での処理をログ出力してくれます。
//もちろん直接書き込むことも可能です。
Log(Format('計算結果:%d+%d=%d',[5,3,i]));
aTest.Free;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
//ログを表示したいフォームにはLog_Eventを設定
//今回は便宜上Form1のUserLog()にログの表示処理をさせます。
Log_Event := UserLog;
end;

procedure TForm1.UserLog(aStr: string);
begin
//ログの表示イベント、ListBox1追加表示されます。
ListBox1.Items.Add(DateTimeToStr(Now)+':'+aStr);
end;

end.
ページ: [1]
WP Forum Server by ForumPress | LucidCrew
バージョン: 1.7.5 ; ページロード: 0.024 sec.