Skip to content

Commit e72ade7

Browse files
author
RandomCrocodile
committed
refactor: replace Confuser.Core.ILogger with Microsoft.Extensions.Logging.ILogger (#64)
Complete migration from the custom 13-method ILogger interface to the standard M.E.L ILogger abstraction across all projects. - Change ConfuserContext.Logger and ConfuserParameters.Logger to M.E.L ILogger - Convert all ~80 call sites: Debug→LogDebug, Info→LogInformation, Warn→LogWarning, Error→LogError, *Exception→swap parameter order - Rewrite MSBuildLogger as MSBuildMelLogger implementing M.E.L ILogger - Rewrite XUnitLogger implementing M.E.L ILogger + IProgressReporter - Remove MelLoggerAdapter (no longer needed — M.E.L is the native type) - Delete Confuser.Core.ILogger, NullLogger (replaced by M.E.L NullLogger) - Add test-results/ and coverage/ to .gitignore
1 parent 56574a2 commit e72ade7

37 files changed

Lines changed: 227 additions & 387 deletions

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,8 @@ packages/
3939
gh-pages/
4040

4141
.idea/
42-
**/*out*
42+
**/*out*
43+
44+
# Local CI artifacts
45+
test-results/
46+
coverage/

Confuser.CLI/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ static int RunProject(ConfuserParameters parameters, bool quiet, int verbosity)
222222
var melLogger = loggerFactory.CreateLogger("ConfuserEx");
223223

224224
var progressReporter = new ConsoleProgressReporter();
225-
parameters.Logger = new MelLoggerAdapter(melLogger);
225+
parameters.Logger = melLogger;
226226
parameters.ProgressReporter = progressReporter;
227227

228228
if (OperatingSystem.IsWindows())

Confuser.Core/ConfuserContext.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using Confuser.Core.Project;
55
using dnlib.DotNet;
66
using dnlib.DotNet.Writer;
7+
using Microsoft.Extensions.Logging;
78

89
namespace Confuser.Core {
910
/// <summary>
@@ -18,7 +19,7 @@ public class ConfuserContext {
1819
/// Gets the logger used for logging events.
1920
/// </summary>
2021
/// <value>The logger.</value>
21-
public ILogger Logger { get; internal set; }
22+
public Microsoft.Extensions.Logging.ILogger Logger { get; internal set; }
2223

2324
/// <summary>
2425
/// Gets the progress reporter used for reporting protection progress.

Confuser.Core/ConfuserEngine.cs

Lines changed: 42 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using dnlib.DotNet;
1111
using dnlib.DotNet.Emit;
1212
using dnlib.DotNet.Writer;
13+
using Microsoft.Extensions.Logging;
1314
using Microsoft.Win32;
1415
using CopyrightAttribute = System.Reflection.AssemblyCopyrightAttribute;
1516
using InformationalAttribute = System.Reflection.AssemblyInformationalVersionAttribute;
@@ -108,7 +109,7 @@ static void RunInternal(ConfuserParameters parameters, CancellationToken token)
108109
var modulePath = Path.Combine(context.BaseDirectory, firstModule.Path);
109110
foreach (var runtimePath in DotNetCorePathResolver.ResolveRuntimePaths(modulePath, context.Logger)) {
110111
asmResolver.PostSearchPaths.Add(runtimePath);
111-
context.Logger.DebugFormat("Auto-detected .NET runtime path: {0}", runtimePath);
112+
context.Logger.LogDebug("Auto-detected .NET runtime path: {0}", runtimePath);
112113
}
113114
}
114115

@@ -117,25 +118,25 @@ static void RunInternal(ConfuserParameters parameters, CancellationToken token)
117118
Marker marker = parameters.GetMarker();
118119

119120
// 2. Discover plugins
120-
context.Logger.Debug("Discovering plugins...");
121+
context.Logger.LogDebug("Discovering plugins...");
121122

122123
IList<Protection> prots;
123124
IList<Packer> packers;
124125
IList<ConfuserComponent> components;
125126
parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components);
126127

127-
context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", prots.Count, packers.Count);
128+
context.Logger.LogInformation("Discovered {0} protections, {1} packers.", prots.Count, packers.Count);
128129

129130
context.CheckCancellation();
130131

131132
// 3. Resolve dependency
132-
context.Logger.Debug("Resolving component dependency...");
133+
context.Logger.LogDebug("Resolving component dependency...");
133134
try {
134135
var resolver = new DependencyResolver(prots);
135136
prots = resolver.SortDependency();
136137
}
137138
catch (CircularDependencyException ex) {
138-
context.Logger.ErrorException("", ex);
139+
context.Logger.LogError(ex, "");
139140
throw new ConfuserException(ex);
140141
}
141142

@@ -148,7 +149,7 @@ static void RunInternal(ConfuserParameters parameters, CancellationToken token)
148149
context.CheckCancellation();
149150

150151
// 4. Load modules
151-
context.Logger.Info("Loading input modules...");
152+
context.Logger.LogInformation("Loading input modules...");
152153
marker.Initialize(prots, packers);
153154
MarkerResult markings = marker.MarkProject(context.Project, context);
154155
context.Modules = new ModuleSorter(markings.Modules).Sort().ToList().AsReadOnly();
@@ -163,13 +164,13 @@ static void RunInternal(ConfuserParameters parameters, CancellationToken token)
163164
context.CheckCancellation();
164165

165166
// 5. Initialize components
166-
context.Logger.Info("Initializing...");
167+
context.Logger.LogInformation("Initializing...");
167168
foreach (ConfuserComponent comp in components) {
168169
try {
169170
comp.Initialize(context);
170171
}
171172
catch (Exception ex) {
172-
context.Logger.ErrorException("Error occurred during initialization of '" + comp.Name + "'.", ex);
173+
context.Logger.LogError(ex, "Error occurred during initialization of '" + comp.Name + "'.");
173174
throw new ConfuserException(ex);
174175
}
175176
context.CheckCancellation();
@@ -178,7 +179,7 @@ static void RunInternal(ConfuserParameters parameters, CancellationToken token)
178179
context.CheckCancellation();
179180

180181
// 6. Build pipeline
181-
context.Logger.Debug("Building pipeline...");
182+
context.Logger.LogDebug("Building pipeline...");
182183
var pipeline = new ProtectionPipeline();
183184
context.Pipeline = pipeline;
184185
foreach (ConfuserComponent comp in components) {
@@ -193,28 +194,28 @@ static void RunInternal(ConfuserParameters parameters, CancellationToken token)
193194
ok = true;
194195
}
195196
catch (AssemblyResolveException ex) {
196-
context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex);
197+
context.Logger.LogError(ex, "Failed to resolve an assembly, check if all dependencies are present in the correct version.");
197198
PrintEnvironmentInfo(context);
198199
}
199200
catch (TypeResolveException ex) {
200-
context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex);
201+
context.Logger.LogError(ex, "Failed to resolve a type, check if all dependencies are present in the correct version.");
201202
PrintEnvironmentInfo(context);
202203
}
203204
catch (MemberRefResolveException ex) {
204-
context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex);
205+
context.Logger.LogError(ex, "Failed to resolve a member, check if all dependencies are present in the correct version.");
205206
PrintEnvironmentInfo(context);
206207
}
207208
catch (IOException ex) {
208-
context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex);
209+
context.Logger.LogError(ex, "An IO error occurred, check if all input/output locations are readable/writable.");
209210
}
210211
catch (OperationCanceledException) {
211-
context.Logger.Error("Operation cancelled.");
212+
context.Logger.LogError("Operation cancelled.");
212213
}
213214
catch (ConfuserException) {
214215
// Exception is already handled/logged, so just ignore and report failure
215216
}
216217
catch (Exception ex) {
217-
context.Logger.ErrorException("Unknown error occurred.", ex);
218+
context.Logger.LogError(ex, "Unknown error occurred.");
218219
}
219220
finally {
220221
if (context.Resolver != null)
@@ -269,27 +270,27 @@ static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext context) {
269270
pipeline.ExecuteStage(PipelineStage.SaveModules, SaveModules, () => getAllDefs(), context);
270271

271272
if (!context.PackerInitiated)
272-
context.Logger.Info("Done.");
273+
context.Logger.LogInformation("Done.");
273274
}
274275

275276
static void Inspection(ConfuserContext context) {
276-
context.Logger.Info("Resolving dependencies...");
277+
context.Logger.LogInformation("Resolving dependencies...");
277278
foreach (var dependency in context.Modules
278279
.SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module)))) {
279280
var resolved = context.Resolver.Resolve(dependency.Item1, dependency.Item2);
280281
if (resolved == null)
281-
context.Logger.WarnFormat("Failed to resolve dependency '{0}' of '{1}'. Some protections may not work correctly.",
282+
context.Logger.LogWarning("Failed to resolve dependency '{0}' of '{1}'. Some protections may not work correctly.",
282283
dependency.Item1.FullName, dependency.Item2.Name);
283284
}
284285

285-
context.Logger.Debug("Checking Strong Name...");
286+
context.Logger.LogDebug("Checking Strong Name...");
286287
foreach (var module in context.Modules) {
287288
CheckStrongName(context, module);
288289
}
289290

290291
var marker = context.Registry.GetService<IMarkerService>();
291292

292-
context.Logger.Debug("Creating global .cctors...");
293+
context.Logger.LogDebug("Creating global .cctors...");
293294
foreach (ModuleDefMD module in context.Modules) {
294295
TypeDef modType = module.GlobalType;
295296
if (modType == null) {
@@ -317,12 +318,12 @@ static void CheckStrongName(ConfuserContext context, ModuleDef module) {
317318
bool isKeyProvided = snKey != null || (snDelaySign && snPubKeyBytes != null);
318319

319320
if (!isKeyProvided && moduleIsSignedOrDelayedSigned)
320-
context.Logger.WarnFormat("[{0}] SN Key or SN public Key is not provided for a signed module, the output may not be working.", module.Name);
321+
context.Logger.LogWarning("[{0}] SN Key or SN public Key is not provided for a signed module, the output may not be working.", module.Name);
321322
else if (isKeyProvided && !moduleIsSignedOrDelayedSigned)
322-
context.Logger.WarnFormat("[{0}] SN Key or SN public Key is provided for an unsigned module, the output may not be working.", module.Name);
323+
context.Logger.LogWarning("[{0}] SN Key or SN public Key is provided for an unsigned module, the output may not be working.", module.Name);
323324
else if (snPubKeyBytes != null && moduleIsSignedOrDelayedSigned &&
324325
!module.Assembly.PublicKey.Data.SequenceEqual(snPubKeyBytes))
325-
context.Logger.WarnFormat("[{0}] Provided SN public Key and signed module's public key do not match, the output may not be working.",
326+
context.Logger.LogWarning("[{0}] Provided SN public Key and signed module's public key do not match, the output may not be working.",
326327
module.Name);
327328
}
328329

@@ -339,7 +340,7 @@ static void CopyPEHeaders(PEHeadersOptions writerOptions, ModuleDefMD module) {
339340
}
340341

341342
static void BeginModule(ConfuserContext context) {
342-
context.Logger.InfoFormat("Processing module '{0}'...", context.CurrentModule.Name);
343+
context.Logger.LogInformation("Processing module '{0}'...", context.CurrentModule.Name);
343344

344345
context.CurrentModuleWriterOptions = new ModuleWriterOptions(context.CurrentModule);
345346
CopyPEHeaders(context.CurrentModuleWriterOptions.PEHeadersOptions, context.CurrentModule);
@@ -394,7 +395,7 @@ static void EndModule(ConfuserContext context) {
394395
output = Path.Combine(context.BaseDirectory, output);
395396
string relativeOutput = Utils.GetRelativePath(output, context.BaseDirectory);
396397
if (relativeOutput is null) {
397-
context.Logger.WarnFormat("Input file is not inside the base directory. Relative path can't be created. Placing file into output root." +
398+
context.Logger.LogWarning("Input file is not inside the base directory. Relative path can't be created. Placing file into output root." +
398399
Environment.NewLine + "Responsible file is: {0}", output);
399400
output = Path.GetFileName(output);
400401
}
@@ -409,7 +410,7 @@ static void EndModule(ConfuserContext context) {
409410
}
410411

411412
static void WriteModule(ConfuserContext context) {
412-
context.Logger.InfoFormat("Writing module '{0}'...", context.CurrentModule.Name);
413+
context.Logger.LogInformation("Writing module '{0}'...", context.CurrentModule.Name);
413414

414415
MemoryStream pdb = null, output = new MemoryStream();
415416

@@ -431,7 +432,7 @@ static void WriteModule(ConfuserContext context) {
431432
}
432433

433434
static void Debug(ConfuserContext context) {
434-
context.Logger.Info("Finalizing...");
435+
context.Logger.LogInformation("Finalizing...");
435436
if (!context.Project.Debug)
436437
return;
437438
for (int i = 0; i < context.OutputModules.Count; i++) {
@@ -447,7 +448,7 @@ static void Debug(ConfuserContext context) {
447448

448449
static void Pack(ConfuserContext context) {
449450
if (context.Packer != null) {
450-
context.Logger.Info("Packing...");
451+
context.Logger.LogInformation("Packing...");
451452
context.Packer.Pack(context, new ProtectionParameters(context.Packer, context.Modules.OfType<IDnlibDef>().ToList()));
452453
}
453454
}
@@ -459,7 +460,7 @@ static void SaveModules(ConfuserContext context) {
459460
string dir = Path.GetDirectoryName(path);
460461
if (!Directory.Exists(dir))
461462
Directory.CreateDirectory(dir);
462-
context.Logger.DebugFormat("Saving to '{0}'...", path);
463+
context.Logger.LogDebug("Saving to '{0}'...", path);
463464
File.WriteAllBytes(path, context.OutputModules[i]);
464465
}
465466
}
@@ -470,13 +471,13 @@ static void SaveModules(ConfuserContext context) {
470471
/// <param name="context">The working context.</param>
471472
static void PrintInfo(ConfuserContext context) {
472473
if (context.PackerInitiated) {
473-
context.Logger.Info("Protecting packer stub...");
474+
context.Logger.LogInformation("Protecting packer stub...");
474475
}
475476
else {
476-
context.Logger.InfoFormat("{0} {1}", Version, Copyright);
477+
context.Logger.LogInformation("{0} {1}", Version, Copyright);
477478

478479
Type mono = Type.GetType("Mono.Runtime");
479-
context.Logger.InfoFormat("Running on {0}, {1}, {2} bits",
480+
context.Logger.LogInformation("Running on {0}, {1}, {2} bits",
480481
Environment.OSVersion,
481482
mono == null ?
482483
".NET Framework v" + Environment.Version :
@@ -543,27 +544,27 @@ static void PrintEnvironmentInfo(ConfuserContext context) {
543544
if (context.PackerInitiated)
544545
return;
545546

546-
context.Logger.Error("---BEGIN DEBUG INFO---");
547+
context.Logger.LogError("---BEGIN DEBUG INFO---");
547548

548-
context.Logger.Error("Installed Framework Versions:");
549+
context.Logger.LogError("Installed Framework Versions:");
549550
foreach (string ver in GetFrameworkVersions()) {
550-
context.Logger.ErrorFormat(" {0}", ver.Trim());
551+
context.Logger.LogError(" {0}", ver.Trim());
551552
}
552-
context.Logger.Error("");
553+
context.Logger.LogError("");
553554

554555
if (context.Resolver != null) {
555-
context.Logger.Error("Cached assemblies:");
556+
context.Logger.LogError("Cached assemblies:");
556557
foreach (AssemblyDef asm in context.InternalResolver.GetCachedAssemblies()) {
557558
if (string.IsNullOrEmpty(asm.ManifestModule.Location))
558-
context.Logger.ErrorFormat(" {0}", asm.FullName);
559+
context.Logger.LogError(" {0}", asm.FullName);
559560
else
560-
context.Logger.ErrorFormat(" {0} ({1})", asm.FullName, asm.ManifestModule.Location);
561+
context.Logger.LogError(" {0} ({1})", asm.FullName, asm.ManifestModule.Location);
561562
foreach (var reference in asm.Modules.OfType<ModuleDefMD>().SelectMany(m => m.GetAssemblyRefs()))
562-
context.Logger.ErrorFormat(" {0}", reference.FullName);
563+
context.Logger.LogError(" {0}", reference.FullName);
563564
}
564565
}
565566

566-
context.Logger.Error("---END DEBUG INFO---");
567+
context.Logger.LogError("---END DEBUG INFO---");
567568
}
568569
}
569570
}

Confuser.Core/ConfuserParameters.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using Confuser.Core.Project;
3+
using Microsoft.Extensions.Logging;
34

45
namespace Confuser.Core {
56
/// <summary>
@@ -16,7 +17,7 @@ public class ConfuserParameters {
1617
/// Gets or sets the logger that used to log the protection process.
1718
/// </summary>
1819
/// <value>The logger, or <c>null</c> if logging is not needed.</value>
19-
public ILogger Logger { get; set; }
20+
public Microsoft.Extensions.Logging.ILogger Logger { get; set; }
2021

2122
/// <summary>
2223
/// Gets or sets the progress reporter used to report protection progress.
@@ -42,8 +43,8 @@ public class ConfuserParameters {
4243
/// Gets the actual non-null logger.
4344
/// </summary>
4445
/// <returns>The logger.</returns>
45-
internal ILogger GetLogger() {
46-
return Logger ?? NullLogger.Instance;
46+
internal Microsoft.Extensions.Logging.ILogger GetLogger() {
47+
return Logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
4748
}
4849

4950
/// <summary>

0 commit comments

Comments
 (0)