Advertisement
Guest User

Logging for D

a guest
May 28th, 2011
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.55 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) {
  19.             engines.length = 1;
  20.             engines[0] = new LogEngine();
  21.         }
  22.     }
  23.    
  24.     void opCall(T...)(string msg, T args)
  25.     {
  26.         if (!IsEnabled) return;
  27.        
  28.         if (recordTemplate != ``) {
  29.             msg = replace(recordTemplate, `$m`,
  30.                 (args.length > 0 ? format(msg, args) : msg)
  31.             );
  32.             msg = replace(msg, `$t`, (cast(DateTime)Clock.currTime()).toSimpleString());
  33.         }
  34.         foreach(eng; engines)
  35.             eng.Write(msg);
  36.     }
  37. }
  38.  
  39. class LogEngine
  40. {
  41.     public void Write(string msg)
  42.     {
  43.         writeln(msg);// default implementation, just output to console
  44.     }
  45. }
  46.  
  47. class FileLogEngine : LogEngine
  48. {
  49.     File f;
  50.     public this(string FileName)
  51.     {
  52.         f = File(FileName, `a`);
  53.     }
  54.    
  55.     override public void Write(string msg)
  56.     {
  57.         f.write(msg ~ "\n");
  58.         f.flush();
  59.     }
  60. }
  61.  
  62. class DBLogEngine : LogEngine
  63. {
  64.     public this(string ConnectionString)
  65.     {
  66.         // open database connection
  67.     }
  68.  
  69.     override public void Write(string msg)
  70.     {
  71.         // write record
  72.     }
  73. }
  74.  
  75. class EmailLogEngine : LogEngine
  76. {
  77.     public this(string host, int port = 25)
  78.     {
  79.         // initialize mail server structures
  80.     }
  81.  
  82.     override public void Write(string msg)
  83.     {
  84.         // send message
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement