Added ThreadedLogger

This commit is contained in:
LukePulverenti Luke Pulverenti luke pulverenti 2012-09-10 15:11:40 -04:00
parent 614668a447
commit b1df61f7ce
5 changed files with 83 additions and 3 deletions

View File

@ -1,13 +1,13 @@
using MediaBrowser.Controller;
using MediaBrowser.Model.DTO;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Entities.Movies;
using MediaBrowser.Model.Entities.TV;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MediaBrowser.Model.Entities.Movies;
namespace MediaBrowser.Api
{

View File

@ -79,6 +79,10 @@ namespace MediaBrowser.Common.Logging
LogEntry(row);
}
protected virtual void Flush()
{
}
public virtual void Dispose()
{
}

View File

@ -7,7 +7,7 @@ namespace MediaBrowser.Common.Logging
/// <summary>
/// Provides a Logger that can write to any Stream
/// </summary>
public class StreamLogger : BaseLogger
public class StreamLogger : ThreadedLogger
{
private Stream Stream { get; set; }
@ -17,7 +17,7 @@ namespace MediaBrowser.Common.Logging
Stream = stream;
}
protected override void LogEntry(LogRow row)
protected override void AsyncLogMessage(LogRow row)
{
byte[] bytes = new UTF8Encoding().GetBytes(row.ToString() + Environment.NewLine);
Stream.Write(bytes, 0, bytes.Length);

View File

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MediaBrowser.Common.Logging
{
public abstract class ThreadedLogger : BaseLogger
{
Thread loggingThread;
Queue<Action> queue = new Queue<Action>();
AutoResetEvent hasNewItems = new AutoResetEvent(false);
volatile bool terminate = false;
bool waiting = false;
public ThreadedLogger()
: base()
{
loggingThread = new Thread(new ThreadStart(ProcessQueue));
loggingThread.IsBackground = true;
loggingThread.Start();
}
void ProcessQueue()
{
while (!terminate)
{
waiting = true;
hasNewItems.WaitOne(10000, true);
waiting = false;
Queue<Action> queueCopy;
lock (queue)
{
queueCopy = new Queue<Action>(queue);
queue.Clear();
}
foreach (var log in queueCopy)
{
log();
}
}
}
protected override void LogEntry(LogRow row)
{
lock (queue)
{
queue.Enqueue(() => AsyncLogMessage(row));
}
hasNewItems.Set();
}
protected abstract void AsyncLogMessage(LogRow row);
protected override void Flush()
{
while (!waiting)
{
Thread.Sleep(1);
}
}
public override void Dispose()
{
Flush();
terminate = true;
hasNewItems.Set();
base.Dispose();
}
}
}

View File

@ -83,6 +83,7 @@
<ItemGroup>
<Compile Include="Kernel\BaseApplicationPaths.cs" />
<Compile Include="Drawing\DrawingUtils.cs" />
<Compile Include="Logging\ThreadedLogger.cs" />
<Compile Include="Net\Handlers\StaticFileHandler.cs" />
<Compile Include="Net\MimeTypes.cs" />
<Compile Include="Properties\Resources.Designer.cs">