Sordie.co.uk

libsassy/libSassy.Log.pas

Raw

{(
 )) libSassy.Log
((    Error/Message logging library
 ))
((  Copyright  Sordie Aranka Solomon-Smith 2015-2016
 ))
((  This work is made available under the terms of the Creative Commons
 )) Attribution-NonCommercial-ShareAlike 3.0 Unported license
((  http://creativecommons.org/licenses/by-nc-sa/3.0/
 )}

unit libSassy.Log;

interface

uses
  Winapi.Windows,

  libSassy.Interfaces,
  libSassy.Streams,
  libSassy.Strings,
  libSassy.Console,
  libSassy.DateTime;

type
{$REGION 'TLog'}
  TLog = class(TInterface)
  private
    fStream: TStream;

    fFormat: String;
  public
    constructor Create(AStream: TStream);
    destructor  Destroy; override;

    procedure Log(Any: array of const; const Prefix: String = 'Log');

    property Stream: TStream read fStream write fStream;

    property Format: String read fFormat write fFormat;
  end;
{$ENDREGION}

{$REGION 'Stock log'}
function  Log: TLog;                overload;
procedure Log(Any: array of const); overload;
{$ENDREGION}

implementation

{$REGION 'TLog'}
constructor TLog.Create;
begin
  inherited Create;

  fStream := AStream;

  fFormat := '%HHHH%:%MM%:%SS% %DD%/%MM%/%YYYY% %PREFIX% ';
end;


destructor TLog.Destroy;
begin
  if Assigned(fStream) and fStream.FreeAfterOp then fStream.Free;

  inherited;
end;

procedure TLog.Log;
var
  s, l, h: String;
begin
  if not Assigned(Stream) then exit;

  s := String.From(Any);
  h := Now.Format(fFormat).Replace('%PREFIX%', Prefix);

  repeat
    l := s.Split(#13#10, False);
    if l.Empty then break;

    l := h + l + #13#10;
    Stream.Write(l[1], l.Size);
  until s.Empty;
end;
{$ENDREGION}

{$REGION 'Stock log'}
var
  _Log: TLog = nil;

function Log: TLog;
begin
  if _Log = nil then
    _Log := TLog.Create(Console);

  Result := _Log;
end;

procedure Log(Any: array of const);
begin
  Log.Log(Any);
end;
{$ENDREGION}

initialization

finalization
  if _Log <> nil then _Log.Free;

end.