Delphi 生成日志记录单元


本文整理自网络,侵删。

 
调用方法:

uses untLog;


log.WriteLog('hello' );





{ ********日志单元******* }
{ }
{ Cobbler }
{ }
{ 版权所有 (C) 2011 Cobbler }
{ }
{ 功能说明: }
{ 日志记录 实现 ILog }
{ }
{ 创建日期:2011-07-11 }
{ 作者:Cobbler }
{ }
{ ******************************************************* }
unit untLog;

interface

uses
  SysUtils, Forms;

Type
  TLog = Class
  private
    procedure WriteToFile(const Msg: string);
  public
    Constructor Create;
    Destructor Destroy; override;
    procedure WriteLog(const Str: String);
    procedure WriteLogFmt(const Str: String; const Args: array of const );
    function GetLogFileName: String;
  End;

var
  flog: TLog=nil;

function log: TLog;

implementation

{ TLog }



function log: TLog;
begin
  if not Assigned(flog) then
    flog := TLog.Create;
  result:=flog;
end;

function TLog.GetLogFileName: String;
var
  Logpath: String;
begin
  Logpath :=ExtractFileDir(ParamStr(0))+ '\Logs\';
  if not DirectoryExists(Logpath) then
    ForceDirectories(Logpath);
  Result := Logpath + FormatDateTime('YYYY-MM-DD', Now) + '.log';
end;

constructor TLog.Create;
begin

end;

destructor TLog.Destroy;
begin

  inherited;
end;

procedure TLog.WriteLog(const Str: String);
begin
  WriteToFile(Str);
end;

procedure TLog.WriteLogFmt(const Str: String; const Args: array of const );
begin
  WriteToFile(Format(Str, Args));
end;

procedure TLog.WriteToFile(const Msg: string);
var
  FileName: String;
  FileHandle: TextFile;
begin
  FileName := GetLogFileName;
  Assignfile(FileHandle, FileName);
  try
    if FileExists(FileName) then
      Append(FileHandle)
    else
      ReWrite(FileHandle);

    WriteLn(FileHandle, FormatDateTime('[HH:MM:SS]', Now) + '  ' + Msg);
  finally
    CloseFile(FileHandle);
  end;
end;

end.

相关阅读 >>

Delphi关于dbgrid和webbrowser的焦点问题

Delphi 在目录后面加上一个 "\"

Delphi 获取自身软件的版本号

Delphi 图像自动调整显示

Delphi 使电脑睡眠代码

Delphi中实现dbgrid列宽度自动调整

Delphi列表控件tlistview定位到某一行

Delphi tfdconnection只能取得50处理

Delphi 如何检测你的电脑日期或时间的变化

Delphi监视注册表

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...