Skip to content

Commit

Permalink
#92 Add Dianoga Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
markgibbons25 committed Jun 19, 2021
1 parent fd64c3b commit 5278c86
Show file tree
Hide file tree
Showing 10 changed files with 180 additions and 27 deletions.
24 changes: 24 additions & 0 deletions src/Dianoga/Default Config Files/Dianoga.Log.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!--
Dianoga Log Configuration
-->
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<log4net>
<appender name="DianogaFileAppender" type="log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging">
<file value="$(dataFolder)/logs/Dianoga.log.{date}.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n"/>
</layout>
<encoding value="utf-8"/>
</appender>
<logger name="Dianoga" additivity="false">
<level value="INFO" />
<appender-ref ref="DianogaFileAppender"/>
<!-- On Azure PaaS you may want to enable this for App Insights logging
<appender-ref ref="AzureFallbackAppender" desc="AzureFallbackAppender" />
-->
</logger>
</log4net>
</sitecore>
</configuration>
1 change: 1 addition & 0 deletions src/Dianoga/Dianoga.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
<Content Include="Dianoga Tools\**\*" Exclude="Dianoga Tools\SVGO\**\*" PackagePath="content\App_Data\Dianoga Tools" />
</ItemGroup>
<ItemGroup>
<None Remove="Default Config Files\Dianoga.DianogaLog.config" />
<None Remove="Default Config Files\Dianoga.TempFilePath.config.example" />
<None Remove="Default Config Files\Dianoga.WebP.CDN.config.disabled" />
<None Remove="Dianoga Tools\libwebp\COPYING.txt" />
Expand Down
128 changes: 128 additions & 0 deletions src/Dianoga/DianogaLog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
using System;
using log4net;
using Sitecore;
using Sitecore.Diagnostics;

namespace Dianoga
{

/// <summary>
/// Dianoga Logger
/// </summary>
public static class DianogaLog
{
/// <summary>
/// The local logger instance.
/// </summary>
private static readonly ILog Log;

/// <summary>
/// Initializes static members of the <see cref="T:Dianoga.DianogaLog" /> class.
/// </summary>
static DianogaLog()
{
Log = LogManager.GetLogger("Dianoga") ?? LoggerFactory.GetLogger(typeof(DianogaLog));
}

/// <summary>
/// Logs info message with context user name.
/// </summary>
/// <param name="message">The message.</param>
public static void Audit(string message)
{
Assert.ArgumentNotNull(message, "message");
Log.Info($"AUDIT ({Context.User.Name}) {message}");
}

/// <summary>
/// Logs error message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void Error(string message, Exception exception = null)
{
Assert.IsNotNull(Log, "Logger implementation was not initialized");
if (exception == null)
{
Log.Error(message);
}
else
{
Log.Error(message, exception);
}
}

/// <summary>
/// Logs information message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void Info(string message, Exception exception = null)
{
Assert.IsNotNull(Log, "Logger implementation was not initialized");
if (exception == null)
{
Log.Info(message);
}
else
{
Log.Info(message, exception);
}
}

/// <summary>
/// Logs warning message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void Warn(string message, Exception exception = null)
{
Assert.IsNotNull(Log, "Logger implementation was not initialized");
if (exception == null)
{
Log.Warn(message);
}
else
{
Log.Warn(message, exception);
}
}

/// <summary>
/// Logs fatal error message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void Fatal(string message, Exception exception = null)
{
Assert.IsNotNull(Log, "Logger implementation was not initialized");
if (exception == null)
{
Log.Fatal(message);
}
else
{
Log.Fatal(message, exception);
}
}

/// <summary>
/// Logs debug message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void Debug(string message, Exception exception = null)
{
Assert.IsNotNull(Log, "Logger implementation was not initialized");
if (exception == null)
{
Log.Debug(message);
}
else
{
Log.Debug(message, exception);
}
}
}

}
2 changes: 1 addition & 1 deletion src/Dianoga/Invokers/GetMediaStreamSync/OptimizeImage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void Process(GetMediaStreamPipelineArgs args)
else
{
var mediaPath = outputStream.MediaItem.MediaPath;
Log.Info($"Dianoga: {mediaPath} cannot be optimized due to media type or path exclusion", this);
DianogaLog.Info($"Dianoga: {mediaPath} cannot be optimized due to media type or path exclusion");
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/Dianoga/Invokers/MediaCacheAsync/OptimizingMediaCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public override bool AddStream(Media media, MediaOptions options, MediaStream st

if (!stream.Stream.CanRead)
{
Log.Warn($"Cannot optimize {media.MediaData.MediaItem.MediaPath} because cache was passed a non readable stream.", this);
DianogaLog.Warn($"Cannot optimize {media.MediaData.MediaItem.MediaPath} because cache was passed a non readable stream.");
return false;
}

Expand Down Expand Up @@ -106,7 +106,7 @@ private void Optimize(SiteContext currentSite, Media media, MediaOptions options

if (optimizedMediaStream == null)
{
Log.Info($"Dianoga: {mediaItem.MediaPath} cannot be optimized due to media type or path exclusion", this);
DianogaLog.Info($"Dianoga: {mediaItem.MediaPath} cannot be optimized due to media type or path exclusion");
cacheRecord = CreateCacheRecord(media, options, backupMediaStream);
}

Expand All @@ -125,7 +125,7 @@ private void Optimize(SiteContext currentSite, Media media, MediaOptions options
catch (Exception ex)
{
// this runs in a background thread, and an exception here would cause IIS to terminate the app pool. Bad! So we catch/log, just in case.
Log.Error($"Dianoga: Exception occurred on the background thread when optimizing: {mediaItem.MediaPath}", ex, this);
DianogaLog.Error($"Dianoga: Exception occurred on the background thread when optimizing: {mediaItem.MediaPath}", ex);
}
finally
{
Expand All @@ -144,7 +144,7 @@ protected virtual void AddToActiveList(MediaCacheRecord record)

if (baseMethod != null)
baseMethod.Invoke(this, new object[] { record });
else Log.Error("Dianoga: Couldn't use malevolent private reflection on AddToActiveList! This may mean Dianoga isn't entirely compatible with this version of Sitecore, though it should only affect a performance optimization.", this);
else DianogaLog.Error("Dianoga: Couldn't use malevolent private reflection on AddToActiveList! This may mean Dianoga isn't entirely compatible with this version of Sitecore, though it should only affect a performance optimization.");

// HEY SITECORE, CAN WE GET THESE VIRTUAL? KTHX.
}
Expand All @@ -155,7 +155,7 @@ protected virtual void RemoveFromActiveList(MediaCacheRecord record)

if (baseMethod != null)
baseMethod.Invoke(this, new object[] { record });
else Log.Error("Dianoga: Couldn't use malevolent private reflection on RemoveFromActiveList! This may mean Dianoga isn't entirely compatible with this version of Sitecore, though it should only affect a performance optimization.", this);
else DianogaLog.Error("Dianoga: Couldn't use malevolent private reflection on RemoveFromActiveList! This may mean Dianoga isn't entirely compatible with this version of Sitecore, though it should only affect a performance optimization.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public virtual void Process(PipelineArgs args)
);

MediaManager.Cache = new OptimizingMediaCache(new MediaOptimizer(), actionBlock);
Log.Info($"Dianoga: Installed optimizing media cache to provide async optimization with max {_maxConcurrentThreads} concurrent threads.", this);
DianogaLog.Info($"Dianoga: Installed optimizing media cache to provide async optimization with max {_maxConcurrentThreads} concurrent threads.");
}
}
}
10 changes: 5 additions & 5 deletions src/Dianoga/MediaOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public virtual MediaStream Process(MediaStream stream, MediaOptions options)

if (!stream.AllowMemoryLoading)
{
Log.Error($"Dianoga: Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {stream.MediaItem.Path}", this);
DianogaLog.Error($"Dianoga: Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {stream.MediaItem.Path}");
return null;
}

Expand All @@ -36,7 +36,7 @@ public virtual MediaStream Process(MediaStream stream, MediaOptions options)
}
catch (Exception exception)
{
Log.Error($"Dianoga: Unable to optimize {stream.MediaItem.MediaPath} due to a processing error! It will be unchanged.", exception, this);
DianogaLog.Error($"Dianoga: Unable to optimize {stream.MediaItem.MediaPath} due to a processing error! It will be unchanged.", exception);
return null;
}
sw.Stop();
Expand All @@ -45,20 +45,20 @@ public virtual MediaStream Process(MediaStream stream, MediaOptions options)
{
if (result.Message.Length > 0)
{
Log.Info($"Dianoga: messages occurred while optimizing {stream.MediaItem.MediaPath}: {result.Message.Trim()}", this);
DianogaLog.Info($"Dianoga: messages occurred while optimizing {stream.MediaItem.MediaPath}: {result.Message.Trim()}");
}

var extension = result.Extension ?? stream.Extension;
if (result.IsOptimized)
{
Log.Info($"Dianoga: optimized {stream.MediaItem.MediaPath}.{stream.MediaItem.Extension} [original size: {GetDimensions(options)} {result.Statistics.SizeBefore} bytes] [final size: {result.Statistics.SizeAfter} bytes] [saved {result.Statistics.BytesSaved} bytes / {result.Statistics.PercentageSaved:p}] [Optimized in {sw.ElapsedMilliseconds}ms] [Extension {extension}]", this);
DianogaLog.Info($"Dianoga: optimized {stream.MediaItem.MediaPath}.{stream.MediaItem.Extension} [original size: {GetDimensions(options)} {result.Statistics.SizeBefore} bytes] [final size: {result.Statistics.SizeAfter} bytes] [saved {result.Statistics.BytesSaved} bytes / {result.Statistics.PercentageSaved:p}] [Optimized in {sw.ElapsedMilliseconds}ms] [Extension {extension}]");
}

return new MediaStream(result.ResultStream, extension, stream.MediaItem);
}

if (!string.IsNullOrWhiteSpace(result.Message))
Log.Warn($"Dianoga: unable to optimize {stream.MediaItem.MediaPath}.{stream.MediaItem.Extension} because {result.Message.Trim()}", this);
DianogaLog.Warn($"Dianoga: unable to optimize {stream.MediaItem.MediaPath}.{stream.MediaItem.Extension} because {result.Message.Trim()}");

// if no message exists that implies that nothing in the dianogaOptimize pipeline acted to optimize - e.g. it's a media type we don't know how to optimize, like PDF.

Expand Down
4 changes: 2 additions & 2 deletions src/Dianoga/Optimizers/CommandLineToolOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public abstract class CommandLineToolOptimizer : OptimizerProcessor
{
private string _pathToExe;

private string _additionalToolArguments;
private string _additionalToolArguments;

public virtual string ExePath
{
Expand Down Expand Up @@ -130,7 +130,7 @@ protected virtual void ExecuteProcess(string arguments)
{

#if DEBUG
Sitecore.Diagnostics.Log.Info($"\"{ExePath} {arguments}\"", this);
DianogaLog.Info($"\"{ExePath} {arguments}\"");
#endif

using (var process = new Process())
Expand Down
2 changes: 1 addition & 1 deletion src/Dianoga/Optimizers/OptimizerProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public virtual void Process(OptimizerArgs args)
args.IsOptimized = false;
args.Stream.Dispose();
args.Stream = originalStream;
Log.Error($"Dianoga: Unable to optimize {args.MediaPath} due to a processing error! It will be unchanged.", ex, this);
DianogaLog.Error($"Dianoga: Unable to optimize {args.MediaPath} due to a processing error! It will be unchanged.", ex);
}
}

Expand Down
24 changes: 12 additions & 12 deletions src/Dianoga/Optimizers/Pipelines/DianogaSvg/SvgoOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;

namespace Dianoga.Optimizers.Pipelines.DianogaSvg

namespace Dianoga.Optimizers.Pipelines.DianogaSvg
{
/// <summary>
/// Uses https://github.com/twardoch/svgop
/// </summary>
public class SvgoOptimizer : CommandLineToolOptimizer
{

/// </summary>
public class SvgoOptimizer : CommandLineToolOptimizer
{

protected override void ProcessOptimizer(OptimizerArgs args)
{
ExecuteProcess(args);
}

}

protected void ExecuteProcess(OptimizerArgs args)
{
using (Process toolProcess = new Process())
Expand All @@ -31,7 +31,7 @@ protected void ExecuteProcess(OptimizerArgs args)
toolProcess.ErrorDataReceived += (sender, eventArgs) => processOutput.Add(eventArgs.Data);

#if DEBUG
Sitecore.Diagnostics.Log.Info($"\"{ExePath} {AdditionalToolArguments}\"", this);
DianogaLog.Info($"\"{ExePath} {AdditionalToolArguments}\"");
#endif

try
Expand Down Expand Up @@ -80,6 +80,6 @@ protected void ExecuteProcess(OptimizerArgs args)
protected override string CreateToolArguments(string tempFilePath, string tempOutputPath)
{
return string.Empty;
}
}
}
}
}
}

0 comments on commit 5278c86

Please sign in to comment.