Extracted Logging into a separate, portable class library

This commit is contained in:
LukePulverenti Luke Pulverenti luke pulverenti 2012-07-30 09:44:28 -04:00
parent 882e20e9a5
commit 7766956274
17 changed files with 246 additions and 215 deletions

View File

@ -6,12 +6,12 @@ using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Common.Json;
using MediaBrowser.Common.Logging;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Progress;
using MediaBrowser.Model.Progress;
using MediaBrowser.Logging;
namespace MediaBrowser.Common.Kernel
{
@ -48,6 +48,22 @@ namespace MediaBrowser.Common.Kernel
}
}
/// <summary>
/// Gets the path to the log directory
/// </summary>
private string LogDirectoryPath
{
get
{
return Path.Combine(ProgramDataPath, "logs");
}
}
/// <summary>
/// Gets or sets the path to the current log file
/// </summary>
private string LogFilePath { get; set; }
/// <summary>
/// Gets the current configuration
/// </summary>
@ -73,12 +89,12 @@ namespace MediaBrowser.Common.Kernel
public BaseKernel()
{
ProgramDataPath = GetProgramDataPath();
Logger.LoggerInstance = new FileLogger(Path.Combine(ProgramDataPath, "Logs"));
}
public virtual void Init(IProgress<TaskProgress> progress)
{
ReloadLogger();
ReloadConfiguration();
ReloadHttpServer();
@ -86,6 +102,24 @@ namespace MediaBrowser.Common.Kernel
ReloadComposableParts();
}
private void ReloadLogger()
{
DisposeLogger();
if (!Directory.Exists(LogDirectoryPath))
{
Directory.CreateDirectory(LogDirectoryPath);
}
DateTime now = DateTime.Now;
LogFilePath = Path.Combine(LogDirectoryPath, now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
FileStream fs = new FileStream(LogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
Logger.LoggerInstance = new StreamLogger(fs);
}
/// <summary>
/// Uses MEF to locate plugins
/// Subclasses can use this to locate types within plugins
@ -213,14 +247,6 @@ namespace MediaBrowser.Common.Kernel
HttpServer = new HttpServer("http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/");
}
private void DisposeHttpServer()
{
if (HttpServer != null)
{
HttpServer.Dispose();
}
}
/// <summary>
/// This snippet will allow any plugin to reference another
/// </summary>
@ -244,6 +270,23 @@ namespace MediaBrowser.Common.Kernel
public void Dispose()
{
DisposeHttpServer();
DisposeLogger();
}
private void DisposeHttpServer()
{
if (HttpServer != null)
{
HttpServer.Dispose();
}
}
private void DisposeLogger()
{
if (Logger.LoggerInstance != null)
{
Logger.LoggerInstance.Dispose();
}
}
}
}

View File

@ -1,55 +0,0 @@
using System;
using System.IO;
using System.Text;
namespace MediaBrowser.Common.Logging
{
public class FileLogger : BaseLogger, IDisposable
{
private string LogDirectory { get; set; }
private string CurrentLogFile { get; set; }
private FileStream FileStream { get; set; }
public FileLogger(string logDirectory)
{
LogDirectory = logDirectory;
}
private void EnsureStream()
{
if (FileStream == null)
{
if (!Directory.Exists(LogDirectory))
{
Directory.CreateDirectory(LogDirectory);
}
DateTime now = DateTime.Now;
CurrentLogFile = Path.Combine(LogDirectory, now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
FileStream = new FileStream(CurrentLogFile, FileMode.Append, FileAccess.Write, FileShare.Read);
}
}
protected override void LogEntry(LogRow row)
{
EnsureStream();
byte[] bytes = new UTF8Encoding().GetBytes(row.ToString() + Environment.NewLine);
FileStream.Write(bytes, 0, bytes.Length);
FileStream.Flush();
}
public void Dispose()
{
if (FileStream != null)
{
FileStream.Dispose();
}
}
}
}

View File

@ -1,118 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MediaBrowser.Common.Logging
{
public struct LogRow
{
const string TimePattern = "h:mm:ss.fff tt d/M/yyyy";
public LogSeverity Severity { get; set; }
public string Message { get; set; }
public string Category { get; set; }
public int ThreadId { get; set; }
public string ThreadName { get; set; }
public DateTime Time { get; set; }
public string ShortMessage
{
get
{
var message = Message;
if (message.Length > 120)
{
message = Message.Substring(0, 120).Replace(Environment.NewLine, " ") + " ... ";
}
return message;
}
}
public string FullDescription
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Time: {0}", Time);
sb.AppendLine();
sb.AppendFormat("Thread Id: {0} {1}", ThreadId, ThreadName);
sb.AppendLine();
sb.AppendLine(Message);
return sb.ToString();
}
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(Time.ToString(TimePattern))
.Append(" , ")
.Append(Enum.GetName(typeof(LogSeverity), Severity))
.Append(" , ")
.Append(Encode(Message))
.Append(" , ")
.Append(Encode(Category))
.Append(" , ")
.Append(ThreadId)
.Append(" , ")
.Append(Encode(ThreadName));
return builder.ToString();
}
private string Encode(string str)
{
return (str ?? "").Replace(",", ",,").Replace(Environment.NewLine, " [n] ");
}
public static LogRow FromString(string message)
{
var split = splitString(message);
return new LogRow()
{
Time = DateTime.ParseExact(split[0], TimePattern, null),
Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), split[1]),
Message = split[2],
Category = split[3],
ThreadId = int.Parse(split[4]),
ThreadName = split[5]
};
}
static string[] splitString(string message)
{
List<string> items = new List<string>();
bool gotComma = false;
StringBuilder currentItem = new StringBuilder();
foreach (var chr in message)
{
if (chr == ',' && gotComma)
{
gotComma = false;
currentItem.Append(',');
}
else if (chr == ',')
{
gotComma = true;
}
else if (gotComma)
{
items.Add(currentItem.ToString().Replace(" [n] ", Environment.NewLine).Trim());
currentItem = new StringBuilder();
gotComma = false;
}
else
{
currentItem.Append(chr);
}
}
items.Add(currentItem.ToString().Replace("[n]", Environment.NewLine).Trim());
return items.ToArray();
}
}
}

View File

@ -48,12 +48,10 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Configuration\BaseApplicationConfiguration.cs" />
<Compile Include="Events\GenericItemEventArgs.cs" />
<Compile Include="Json\JsonSerializer.cs" />
<Compile Include="Kernel\BaseKernel.cs" />
<Compile Include="Kernel\KernelContext.cs" />
<Compile Include="Logging\LogSeverity.cs" />
<Compile Include="Net\CollectionExtensions.cs" />
<Compile Include="Net\Handlers\BaseEmbeddedResourceHandler.cs" />
<Compile Include="Net\Handlers\BaseHandler.cs" />
@ -62,18 +60,17 @@
<Compile Include="Net\Request.cs" />
<Compile Include="Net\RequestContext.cs" />
<Compile Include="Net\StreamExtensions.cs" />
<Compile Include="Logging\BaseLogger.cs" />
<Compile Include="Logging\FileLogger.cs" />
<Compile Include="Logging\Logger.cs" />
<Compile Include="Logging\LogRow.cs" />
<Compile Include="Plugins\BasePlugin.cs" />
<Compile Include="Progress\TaskProgress.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Logging\MediaBrowser.Logging.csproj">
<Project>{37032b77-fe2e-4ec5-b7e4-baf634443578}</Project>
<Name>MediaBrowser.Logging</Name>
</ProjectReference>
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj">
<Project>{7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b}</Project>
<Name>MediaBrowser.Model</Name>

View File

@ -1,5 +1,4 @@
using System.Collections.Generic;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Configuration;
namespace MediaBrowser.Controller.Configuration

View File

@ -1,11 +1,10 @@
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace MediaBrowser.Common.Logging
namespace MediaBrowser.Logging
{
public abstract class BaseLogger
public abstract class BaseLogger : IDisposable
{
public LogSeverity LogSeverity { get; set; }
@ -27,23 +26,16 @@ namespace MediaBrowser.Common.Logging
public void LogException(string message, Exception exception, params object[] paramList)
{
StringBuilder builder = new StringBuilder();
if (exception != null)
{
var trace = new StackTrace(exception, true);
builder.AppendFormat("Exception. Type={0} Msg={1} Src={2} Method={5} Line={6} Col={7}{4}StackTrace={4}{3}",
builder.AppendFormat("Exception. Type={0} Msg={1} StackTrace={3}{2}",
exception.GetType().FullName,
exception.Message,
exception.Source,
exception.StackTrace,
Environment.NewLine,
trace.GetFrame(0).GetMethod().Name,
trace.GetFrame(0).GetFileLineNumber(),
trace.GetFrame(0).GetFileColumnNumber());
Environment.NewLine);
}
StackFrame frame = new StackFrame(1);
message = string.Format(message, paramList);
LogError(string.Format("{0} ( {1} )", message, builder));
@ -68,13 +60,17 @@ namespace MediaBrowser.Common.Logging
Message = message,
Category = string.Empty,
ThreadId = currentThread.ManagedThreadId,
ThreadName = currentThread.Name,
//ThreadName = currentThread.Name,
Time = DateTime.Now
};
LogEntry(row);
}
public virtual void Dispose()
{
}
protected abstract void LogEntry(LogRow row);
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Text;
namespace MediaBrowser.Logging
{
public struct LogRow
{
const string TimePattern = "h:mm:ss.fff tt d/M/yyyy";
public LogSeverity Severity { get; set; }
public string Message { get; set; }
public string Category { get; set; }
public int ThreadId { get; set; }
public string ThreadName { get; set; }
public DateTime Time { get; set; }
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(Time.ToString(TimePattern))
.Append(" , ")
.Append(Enum.GetName(typeof(LogSeverity), Severity))
.Append(" , ")
.Append(Encode(Message))
.Append(" , ")
.Append(Encode(Category))
.Append(" , ")
.Append(ThreadId)
.Append(" , ")
.Append(Encode(ThreadName));
return builder.ToString();
}
private string Encode(string str)
{
return (str ?? "").Replace(",", ",,").Replace(Environment.NewLine, " [n] ");
}
}
}

View File

@ -1,6 +1,6 @@
using System;
namespace MediaBrowser.Common.Logging
namespace MediaBrowser.Logging
{
[Flags]
public enum LogSeverity

View File

@ -1,6 +1,6 @@
using System;
namespace MediaBrowser.Common.Logging
namespace MediaBrowser.Logging
{
public static class Logger
{

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{37032B77-FE2E-4EC5-B7E4-BAF634443578}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MediaBrowser.Logging</RootNamespace>
<AssemblyName>MediaBrowser.Logging</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Profile95</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
</ItemGroup>
<ItemGroup>
<Compile Include="BaseLogger.cs" />
<Compile Include="Logger.cs" />
<Compile Include="LogRow.cs" />
<Compile Include="LogSeverity.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StreamLogger.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,30 @@
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MediaBrowser.Logging")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MediaBrowser.Logging")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,32 @@
using System;
using System.IO;
using System.Text;
namespace MediaBrowser.Logging
{
public class StreamLogger : BaseLogger
{
private Stream Stream { get; set; }
public StreamLogger(Stream stream)
: base()
{
Stream = stream;
}
protected override void LogEntry(LogRow row)
{
byte[] bytes = new UTF8Encoding().GetBytes(row.ToString() + Environment.NewLine);
Stream.Write(bytes, 0, bytes.Length);
Stream.Flush();
}
public override void Dispose()
{
base.Dispose();
Stream.Dispose();
}
}
}

View File

@ -1,6 +1,6 @@
using MediaBrowser.Common.Logging;
using MediaBrowser.Logging;
namespace MediaBrowser.Common.Configuration
namespace MediaBrowser.Model.Configuration
{
/// <summary>
/// Serves as a common base class for the Server and UI application Configurations

View File

@ -10,7 +10,7 @@
<RootNamespace>MediaBrowser.Model</RootNamespace>
<AssemblyName>MediaBrowser.Model</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Profile4</TargetFrameworkProfile>
<TargetFrameworkProfile>Profile95</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
@ -33,8 +33,13 @@
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
<ProjectReference Include="..\MediaBrowser.Logging\MediaBrowser.Logging.csproj">
<Project>{37032b77-fe2e-4ec5-b7e4-baf634443578}</Project>
<Name>MediaBrowser.Logging</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Compile Include="Configuration\BaseApplicationConfiguration.cs" />
<Compile Include="Configuration\UserConfiguration.cs" />
<Compile Include="Entities\ApiBaseItem.cs" />
<Compile Include="Entities\Audio.cs" />
@ -48,6 +53,7 @@
<Compile Include="Entities\Year.cs" />
<Compile Include="Plugins\BasePluginConfiguration.cs" />
<Compile Include="Plugins\PluginInfo.cs" />
<Compile Include="Progress\TaskProgress.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Users\User.cs" />
<Compile Include="Users\UserItemData.cs" />

View File

@ -1,5 +1,5 @@

namespace MediaBrowser.Common.Progress
namespace MediaBrowser.Model.Progress
{
/// <summary>
/// Represents a generic progress class that can be used with IProgress

View File

@ -1,6 +1,6 @@
using System;
using MediaBrowser.Controller;
using MediaBrowser.Common.Progress;
using MediaBrowser.Model.Progress;
namespace MediaBrowser.Program
{
@ -28,6 +28,8 @@ namespace MediaBrowser.Program
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
kernel.Dispose();
}
}
}

View File

@ -21,6 +21,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Common", "Medi
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Model", "MediaBrowser.Model\MediaBrowser.Model.csproj", "{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Logging", "MediaBrowser.Logging\MediaBrowser.Logging.csproj", "{37032B77-FE2E-4EC5-B7E4-BAF634443578}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -35,6 +37,10 @@ Global
{32DFC600-CD2F-4B2D-B39A-3B4C6C32F9B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{32DFC600-CD2F-4B2D-B39A-3B4C6C32F9B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{32DFC600-CD2F-4B2D-B39A-3B4C6C32F9B4}.Release|Any CPU.Build.0 = Release|Any CPU
{37032B77-FE2E-4EC5-B7E4-BAF634443578}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37032B77-FE2E-4EC5-B7E4-BAF634443578}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37032B77-FE2E-4EC5-B7E4-BAF634443578}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37032B77-FE2E-4EC5-B7E4-BAF634443578}.Release|Any CPU.Build.0 = Release|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.ActiveCfg = Release|Any CPU