Advertisement
thornik

Log library

May 29th, 2011
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.98 KB | None | 0 0
  1. module log;
  2.  
  3. import std.stdio;
  4. import std.array;
  5. import std.conv;
  6. import std.string;
  7. import std.datetime;
  8.  
  9. class Log
  10. {
  11.     string recordTemplate = `$t - $m`;// if not empty, then used as a template for output record;
  12.     public LogEngine[] engines;
  13.     bool IsEnabled = true;// Set to false if logging is not needed
  14.    
  15.     public this(LogEngine[] eng ...)
  16.     {
  17.         engines = eng;
  18.         if (engines.length == 0) engines ~= new LogEngine();
  19.     }
  20.  
  21. version(log) {
  22.     void opCall(T...)(string msg, T args)
  23.     {
  24.         if (!IsEnabled) return;
  25.        
  26.         if (recordTemplate != ``) {
  27.             msg = replace(recordTemplate, `$m`,
  28.                 (args.length > 0 ? format(msg, args) : msg)
  29.             );
  30.             msg = replace(msg, `$t`, (cast(DateTime)Clock.currTime()).toSimpleString());
  31.         }
  32.         foreach(eng; engines)
  33.             eng.Write(msg);
  34.     }
  35. } else {
  36.     void opCall(...){}// hope D optimizes empty function calls?
  37. }
  38.  
  39. }
  40.  
  41. class LogEngine
  42. {
  43.     public void Write(string msg)
  44.     {
  45.         writeln(msg);// default implementation, just output to console
  46.     }
  47. }
  48.  
  49. class FileLogEngine : LogEngine
  50. {
  51.     File f;
  52.     public this(string FileName)
  53.     {
  54.         f = File(FileName, `a`);
  55.     }
  56.    
  57.     override public void Write(string msg)
  58.     {
  59.         f.write(msg ~ "\n");
  60.         f.flush();
  61.     }
  62. }
  63.  
  64. class DBLogEngine : LogEngine
  65. {
  66.     public this(string ConnectionString)
  67.     {
  68.         // open database connection
  69.     }
  70.  
  71.     override public void Write(string msg)
  72.     {
  73.         // write record
  74.     }
  75. }
  76.  
  77. class EmailLogEngine : LogEngine
  78. {
  79.     public this(string host, int port = 25)
  80.     {
  81.         // initialize mail server structures
  82.     }
  83.  
  84.     override public void Write(string msg)
  85.     {
  86.         // send message
  87.     }
  88. }
  89.  
  90. class WebLogEngine : LogEngine
  91. {
  92.     public this(string URL)
  93.     {
  94.     }
  95.  
  96.     override public void Write(string msg)
  97.     {
  98.         // call webservice in URL with msg
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement