Simply3DScan
LoggerTask.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Concurrent;
3 using System.IO;
4 
5 namespace Logging
6 {
10  class LoggerTask
11  {
12  private readonly StreamWriter streamWriter;
13  private readonly object lockObject = new Object();
14  private bool stop;
15 
22  public bool IsStopped { get; private set; }
23 
24  private readonly BlockingCollection<LoggerInfo> logEntries = new BlockingCollection<LoggerInfo>();
25 
31  public LoggerTask(string folder, string fileName)
32  {
33  fileName = String.IsNullOrWhiteSpace(fileName)
34  ? $"{DateTime.Now.ToFileTime()}_DefaultLog.log"
35  : $"{DateTime.Now.ToFileTime()}_{Path.GetFileName(fileName)}.log";
36  this.streamWriter = new StreamWriter(Path.Combine(folder, fileName));
37  }
38 
43  public void DoWork()
44  {
45  while (!this.stop)
46  {
47  LoggerInfo logInfo = this.logEntries.Take();
48  if (null != logInfo)
49  this.Log(logInfo);
50  }
51 
52  if (this.streamWriter == null)
53  return;
54 
55  lock (this.lockObject)
56  {
57  this.streamWriter.Close();
58  }
59 
60  this.IsStopped = true;
61  }
62 
67  private void Log(LoggerInfo logInfo)
68  {
69  lock (this.lockObject)
70  {
71  this.streamWriter.WriteLine(logInfo.ToString());
72  this.streamWriter.Flush();
73  }
74  }
75 
80  internal void EnqueueObject(LoggerInfo loggerInfo)
81  {
82  this.logEntries.Add(loggerInfo);
83  }
84 
88  internal void Stop()
89  {
90  this.stop = true;
91  this.logEntries.Add(null);
92  }
93  }
94 }
void EnqueueObject(LoggerInfo loggerInfo)
Enqueues the object.
Definition: LoggerTask.cs:80
Class for holding log information
Definition: LoggerInfo.cs:8
LoggerTask(string folder, string fileName)
Initializes a new instance of the LoggerTask class.
Definition: LoggerTask.cs:31
Definition: Logger.cs:5
void Stop()
Stops this instance.
Definition: LoggerTask.cs:88
bool IsStopped
Gets a value indicating whether this instance is stopped.
Definition: LoggerTask.cs:22
void DoWork()
Does the work. Events to log are filled in a concurrent queue and then read here in serial order...
Definition: LoggerTask.cs:43
Task for logging events
Definition: LoggerTask.cs:10
override string ToString()
Returns a System.String that represents this instance.
Definition: LoggerInfo.cs:42