Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
Use NLog and implement rolling logs to limit max file size (sometimes…
Browse files Browse the repository at this point in the history
… these can get huge!)
  • Loading branch information
caesay committed Dec 19, 2021
1 parent fac0799 commit 2299ecd
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 57 deletions.
76 changes: 76 additions & 0 deletions src/Update/Logging.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.IO;
using NLog.Config;
using NLog.Targets;
using Squirrel.SimpleSplat;

namespace Squirrel.Update
{
class SetupLogLogger : ILogger
{
public LogLevel Level { get; set; }

private readonly NLog.Logger _log;

public SetupLogLogger(bool saveInTemp, UpdateAction action)
{
var dir = saveInTemp ?
Utility.GetTempDirectory(null).FullName :
AssemblyRuntimeInfo.BaseDirectory;

string name, archivename;
if (saveInTemp || action == UpdateAction.Unset) {
name = "Squirrel.log";
archivename = "Squirrel.{###}.log";
} else {
name = $"Squirrel-{action}.log";
archivename = $"Squirrel-{action}.{{###}}.log";
}

// https://gist.github.com/chrisortman/1092889
SimpleConfigurator.ConfigureForTargetLogging(
new FileTarget() {
FileName = Path.Combine(dir, name),
Layout = new NLog.Layouts.SimpleLayout("${longdate} [${level:uppercase=true}] - ${message}"),
ArchiveFileName = Path.Combine(dir, archivename),
ArchiveAboveSize = 4_000_000 /* 4 MB */,
ArchiveNumbering = ArchiveNumberingMode.Sequence,
ConcurrentWrites = true, // should allow multiple processes to use the same file
KeepFileOpen = true,
MaxArchiveFiles = 3 /* MAX 16mb of log data per "action" */,
},
NLog.LogLevel.Debug
);

_log = NLog.LogManager.GetLogger("SetupLogLogger");
}

public void Write(string message, LogLevel logLevel)
{
if (logLevel < Level) {
return;
}

switch (logLevel) {
case LogLevel.Debug:
_log.Debug(message);
break;
case LogLevel.Info:
_log.Info(message);
break;
case LogLevel.Warn:
_log.Warn(message);
break;
case LogLevel.Error:
_log.Error(message);
break;
case LogLevel.Fatal:
_log.Fatal(message);
break;
default:
_log.Info(message);
break;
}
}
}
}
66 changes: 9 additions & 57 deletions src/Update/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,8 @@ static int main(string[] args)
try {
opt = new StartupOption(args);
} catch (Exception ex) {
using (var logger = new SetupLogLogger(true, "OptionParsing") { Level = LogLevel.Info }) {
SquirrelLocator.CurrentMutable.Register(() => logger, typeof(Squirrel.SimpleSplat.ILogger));
logger.Write($"Failed to parse command line options. {ex.Message}", LogLevel.Error);
}
var logp = new SetupLogLogger(true, UpdateAction.Unset) { Level = LogLevel.Info };
logp.Write($"Failed to parse command line options. {ex.Message}", LogLevel.Error);
throw;
}

Expand All @@ -53,15 +51,14 @@ static int main(string[] args)
bool logToTemp = opt.updateAction == UpdateAction.Uninstall
|| opt.updateAction == UpdateAction.Setup;

using (var logger = new SetupLogLogger(logToTemp, opt.updateAction.ToString()) { Level = LogLevel.Info }) {
SquirrelLocator.CurrentMutable.Register(() => logger, typeof(SimpleSplat.ILogger));
var logger = new SetupLogLogger(logToTemp, opt.updateAction) { Level = LogLevel.Info };
SquirrelLocator.CurrentMutable.Register(() => logger, typeof(SimpleSplat.ILogger));

try {
return executeCommandLine(args);
} catch (Exception ex) {
logger.Write("Finished with unhandled exception: " + ex, LogLevel.Fatal);
throw;
}
try {
return executeCommandLine(args);
} catch (Exception ex) {
logger.Write("Finished with unhandled exception: " + ex, LogLevel.Fatal);
throw;
}
}

Expand Down Expand Up @@ -580,49 +577,4 @@ public void Raise(int i)
Progress.Invoke(this, i);
}
}

class SetupLogLogger : SimpleSplat.ILogger, IDisposable
{
TextWriter inner;
readonly object gate = 42;
public SimpleSplat.LogLevel Level { get; set; }

public SetupLogLogger(bool saveInTemp, string commandSuffix = null)
{
for (int i = 0; i < 10; i++) {
try {
var dir = saveInTemp ?
Path.GetTempPath() :
AssemblyRuntimeInfo.BaseDirectory;
var fileName = commandSuffix == null ? String.Format($"Squirrel.{i}.log", i) : String.Format($"Squirrel-{commandSuffix}.{i}.log", i);
var file = Path.Combine(dir, fileName.Replace(".0.log", ".log"));
var str = File.Open(file, FileMode.Append, FileAccess.Write, FileShare.Read);
inner = new StreamWriter(str, Encoding.UTF8, 4096, false) { AutoFlush = true };
return;
} catch (Exception ex) {
// Didn't work? Keep going
Console.Error.WriteLine("Couldn't open log file, trying new file: " + ex.ToString());
}
}

inner = Console.Error;
}

public void Write(string message, LogLevel logLevel)
{
if (logLevel < Level) {
return;
}

lock (gate) inner.WriteLine($"[{DateTime.Now.ToString("dd/MM/yy HH:mm:ss")}] {logLevel.ToString().ToLower()}: {message}");
}

public void Dispose()
{
lock (gate) {
inner.Flush();
inner.Dispose();
}
}
}
}
1 change: 1 addition & 0 deletions src/Update/Update.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NLog" Version="5.0.0-preview.3" />
<PackageReference Include="System.Drawing.Common" Version="6.0.0" />
<PackageReference Include="Vanara.PInvoke.User32" Version="3.3.14" />
</ItemGroup>
Expand Down

0 comments on commit 2299ecd

Please sign in to comment.