Skip to content

Commit

Permalink
fix: Wrong Logging usage (#2929)
Browse files Browse the repository at this point in the history
- fix combination of string interpolation with parameters in logging
  call in Stryker.Core/Stryker.Core/TestRunners/VsTest/VsTestRunner.cs
- harmonize logging calls:
  * remove string interpolation
  * use parameter name instead of index
  * use constant log messages
  • Loading branch information
Dirk-Peters-BF committed May 3, 2024
1 parent f422eda commit b5f9aa5
Show file tree
Hide file tree
Showing 35 changed files with 558 additions and 319 deletions.
2 changes: 1 addition & 1 deletion src/Stryker.CLI/Stryker.CLI/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -1731,4 +1731,4 @@
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ public async Task Save(JsonReport report, string version)
}
catch (RequestFailedException ex)
{
_logger.LogError("Failed to allocated file in azure file share at {reportUri} with error code {errorCode}", uri, ex.ErrorCode);
_logger.LogError(
"Failed to allocated file in azure file share at {reportUri} with error code {errorCode}",
uri, ex.ErrorCode);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ public string GetCurrentBranchName()
string branchName = null;
if (Repository?.Branches?.FirstOrDefault(b => b.IsCurrentRepositoryHead) is var identifiedBranch && identifiedBranch is { })
{
_logger.LogDebug("{0} identified as current branch", identifiedBranch.FriendlyName);
_logger.LogDebug("{BranchName} identified as current branch", identifiedBranch.FriendlyName);
branchName = identifiedBranch.FriendlyName;
}

if (string.IsNullOrWhiteSpace(branchName))
{
_logger.LogDebug("Could not locate the current branch name, using project version instead: {0}", _options.ProjectVersion);
_logger.LogDebug("Could not locate the current branch name, using project version instead: {ProjectVersion}", _options.ProjectVersion);
branchName = _options.ProjectVersion;
}

Expand Down
67 changes: 44 additions & 23 deletions src/Stryker.Core/Stryker.Core/Compiling/CSharpRollbackProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ namespace Stryker.Core.Compiling
{
public interface ICSharpRollbackProcess
{
CSharpRollbackProcessResult Start(CSharpCompilation compiler, ImmutableArray<Diagnostic> diagnostics, bool lastAttempt, bool devMode);
CSharpRollbackProcessResult Start(CSharpCompilation compiler, ImmutableArray<Diagnostic> diagnostics,
bool lastAttempt, bool devMode);

SyntaxTree CleanUpFile(SyntaxTree file);
}

Expand All @@ -34,31 +36,36 @@ public CSharpRollbackProcess()
RollBackedIds = new List<int>();
}

public CSharpRollbackProcessResult Start(CSharpCompilation compiler, ImmutableArray<Diagnostic> diagnostics, bool lastAttempt, bool devMode)
public CSharpRollbackProcessResult Start(CSharpCompilation compiler, ImmutableArray<Diagnostic> diagnostics,
bool lastAttempt, bool devMode)
{
// match the diagnostics with their syntax trees
var syntaxTreeMapping = compiler.SyntaxTrees.ToDictionary<SyntaxTree, SyntaxTree, ICollection<Diagnostic>>(syntaxTree => syntaxTree, _ => new Collection<Diagnostic>());
var syntaxTreeMapping =
compiler.SyntaxTrees.ToDictionary<SyntaxTree, SyntaxTree, ICollection<Diagnostic>>(
syntaxTree => syntaxTree, _ => new Collection<Diagnostic>());

foreach (var diagnostic in diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error))
{
{
if (diagnostic.Location.SourceTree == null)
{
Logger.LogWarning("General compilation error: {0}", diagnostic.GetMessage());
Logger.LogWarning("General compilation error: {Message}", diagnostic.GetMessage());
continue;
}

syntaxTreeMapping[diagnostic.Location.SourceTree].Add(diagnostic);
}

// remove the broken mutations from the syntax trees
foreach (var syntaxTreeMap in syntaxTreeMapping.Where(x => x.Value.Any()))
{
var originalTree = syntaxTreeMap.Key;
Logger.LogDebug($"RollBacking mutations from {originalTree.FilePath}.");
Logger.LogDebug("RollBacking mutations from {FilePath}.", originalTree.FilePath);
if (devMode)
{
DumpBuildErrors(syntaxTreeMap);
Logger.LogTrace("source {1}", originalTree);
Logger.LogTrace("source {OriginalTree}", originalTree);
}

var updatedSyntaxTree = RemoveCompileErrorMutations(originalTree, syntaxTreeMap.Value);

if (updatedSyntaxTree == originalTree && lastAttempt)
Expand All @@ -68,7 +75,7 @@ public CSharpRollbackProcessResult Start(CSharpCompilation compiler, ImmutableAr
throw new CompilationException("Internal error due to compile error.");
}

Logger.LogTrace("RolledBack to {0}", updatedSyntaxTree.ToString());
Logger.LogTrace("RolledBack to {UpdatedSyntaxTree}", updatedSyntaxTree.ToString());

// update the compiler object with the new syntax tree
compiler = compiler.ReplaceSyntaxTree(originalTree, updatedSyntaxTree);
Expand All @@ -88,6 +95,7 @@ public CSharpRollbackProcessResult Start(CSharpCompilation compiler, ImmutableAr
{
return (startNode, info.Id.Value);
}

for (var node = startNode; node != null; node = node.Parent)
{
info = ExtractMutationInfo(node);
Expand Down Expand Up @@ -134,7 +142,8 @@ private MutantInfo ExtractMutationInfo(SyntaxNode node)
return new MutantInfo();
}

Logger.LogDebug("Found mutant {id} of type '{type}' controlled by '{engine}'.", info.Id, info.Type, info.Engine);
Logger.LogDebug("Found mutant {id} of type '{type}' controlled by '{engine}'.", info.Id, info.Type,
info.Engine);

return info;
}
Expand All @@ -143,11 +152,15 @@ private static SyntaxNode FindEnclosingMember(SyntaxNode node)
{
for (var currentNode = node; currentNode != null; currentNode = currentNode.Parent)
{
if (currentNode.IsKind(SyntaxKind.MethodDeclaration) || currentNode.IsKind(SyntaxKind.GetAccessorDeclaration) || currentNode.IsKind(SyntaxKind.SetAccessorDeclaration) || currentNode.IsKind(SyntaxKind.ConstructorDeclaration))
if (currentNode.IsKind(SyntaxKind.MethodDeclaration) ||
currentNode.IsKind(SyntaxKind.GetAccessorDeclaration) ||
currentNode.IsKind(SyntaxKind.SetAccessorDeclaration) ||
currentNode.IsKind(SyntaxKind.ConstructorDeclaration))
{
return currentNode;
}
}

// return the whole file if not found
return node.SyntaxTree.GetRoot();
}
Expand All @@ -165,22 +178,24 @@ private IList<MutantInfo> ScanAllMutationsIfsAndIds(SyntaxNode node)
{
scan.Add(info);
}

return scan;
}

private void DumpBuildErrors(KeyValuePair<SyntaxTree, ICollection<Diagnostic>> syntaxTreeMap)
{
Logger.LogDebug($"Dumping build error in file");
Logger.LogDebug("Dumping build error in file");
var sourceLines = syntaxTreeMap.Key.ToString().Split("\n");
foreach (var diagnostic in syntaxTreeMap.Value)
{
var fileLinePositionSpan = diagnostic.Location.GetMappedLineSpan();
Logger.LogDebug($"Error :{diagnostic.GetMessage()}, {fileLinePositionSpan}");
Logger.LogDebug("Error :{Message}, {fileLinePositionSpan}",
diagnostic.GetMessage(), fileLinePositionSpan);
for (var i = Math.Max(0, fileLinePositionSpan.StartLinePosition.Line - 1);
i <= Math.Min(fileLinePositionSpan.EndLinePosition.Line + 1, sourceLines.Length - 1);
i++)
i <= Math.Min(fileLinePositionSpan.EndLinePosition.Line + 1, sourceLines.Length - 1);
i++)
{
Logger.LogDebug($"{i + 1}: {sourceLines[i]}");
Logger.LogDebug("{index}: {sourceLine}", i + 1, sourceLines[i]);
}
}

Expand All @@ -191,7 +206,8 @@ private SyntaxTree RemoveCompileErrorMutations(SyntaxTree originalTree, IEnumera
{
var rollbackRoot = originalTree.GetRoot();
// find all if statements to remove
var brokenMutations = IdentifyMutationsAndFlagForRollback(diagnosticInfo, rollbackRoot, out var diagnostics);
var brokenMutations =
IdentifyMutationsAndFlagForRollback(diagnosticInfo, rollbackRoot, out var diagnostics);

if (brokenMutations.Count == 0)
{
Expand All @@ -208,6 +224,7 @@ private SyntaxTree RemoveCompileErrorMutations(SyntaxTree originalTree, IEnumera
// remove the mutated node using its MutantPlacer remove method and update the tree
trackedTree = trackedTree.ReplaceNode(nodeToRemove, MutantPlacer.RemoveMutant(nodeToRemove));
}

return trackedTree.SyntaxTree;
}

Expand Down Expand Up @@ -235,19 +252,20 @@ private Collection<SyntaxNode> ScanForSuspiciousMutations(Diagnostic[] diagnosti
// we have to remove every mutation
var errorLocation = diagnostic.Location.GetMappedLineSpan();
Logger.LogWarning(
"Stryker.NET encountered a compile error in {0} (at {1}:{2}) with message: {3} (Source code: {4})",
"Stryker.NET encountered a compile error in {Path} (at {Line}:{StartCharacter}) with message: {Message} (Source code: {BrokenMutation})",
errorLocation.Path, errorLocation.StartLinePosition.Line,
errorLocation.StartLinePosition.Character, diagnostic.GetMessage(), brokenMutation);

Logger.LogInformation(
$"Safe Mode! Stryker will flag mutations in {DisplayName(initNode)} as compile error.");
"Safe Mode! Stryker will flag mutations in {DisplayName} as compile error.",
DisplayName(initNode));
// backup, remove all mutations in the node
foreach (var mutant in scan.Where(mutant => !suspiciousMutations.Contains(mutant.Node)))
{
suspiciousMutations.Add(mutant.Node);
if (mutant.Id != -1)
{
RollBackedIds.Add(mutant.Id.Value);
RollBackedIds.Add(mutant.Id!.Value);
}
}
}
Expand All @@ -267,9 +285,10 @@ public SyntaxTree CleanUpFile(SyntaxTree file)
suspiciousMutations.Add(mutant.Node);
if (mutant.Id != -1)
{
RollBackedIds.Add(mutant.Id.Value);
RollBackedIds.Add(mutant.Id!.Value);
}
}

// mark the broken mutation nodes to track
var trackedTree = rollbackRoot.TrackNodes(suspiciousMutations);
foreach (var brokenMutation in suspiciousMutations)
Expand All @@ -279,6 +298,7 @@ public SyntaxTree CleanUpFile(SyntaxTree file)
// remove the mutated node using its MutantPlacer remove method and update the tree
trackedTree = trackedTree.ReplaceNode(nodeToRemove, MutantPlacer.RemoveMutant(nodeToRemove));
}

return file.WithRootAndOptions(trackedTree, file.Options);
}

Expand All @@ -288,10 +308,11 @@ initNode switch
MethodDeclarationSyntax method => $"{method.Identifier}",
ConstructorDeclarationSyntax constructor => $"{constructor.Identifier}",
AccessorDeclarationSyntax accessor => $"{accessor.Keyword} {accessor.Keyword}",
not null => initNode.Parent == null ? "whole file" : "the current node",
not null => initNode.Parent == null ? "whole file" : "the current node",
};

private Collection<SyntaxNode> IdentifyMutationsAndFlagForRollback(IEnumerable<Diagnostic> diagnosticInfo, SyntaxNode rollbackRoot, out Diagnostic[] diagnostics)
private Collection<SyntaxNode> IdentifyMutationsAndFlagForRollback(IEnumerable<Diagnostic> diagnosticInfo,
SyntaxNode rollbackRoot, out Diagnostic[] diagnostics)
{
var brokenMutations = new Collection<SyntaxNode>();
diagnostics = diagnosticInfo as Diagnostic[] ?? diagnosticInfo.ToArray();
Expand Down Expand Up @@ -330,7 +351,7 @@ private void FlagChildrenMutationsForRollback(SyntaxNode mutationIf, Collection<
brokenMutations.Add(mutant.Node);
if (mutant.Id != -1)
{
RollBackedIds.Add(mutant.Id.Value);
RollBackedIds.Add(mutant.Id!.Value);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public CompilingProcessResult Compile(IEnumerable<SyntaxTree> syntaxTrees, Strea
// If compiling failed and the error has no location, log and throw exception.
if (!emitResult.Success && emitResult.Diagnostics.Any(diagnostic => diagnostic.Location == Location.None && diagnostic.Severity == DiagnosticSeverity.Error))
{
_logger.LogError("Failed to build the mutated assembly due to unrecoverable error: {0}",
_logger.LogError("Failed to build the mutated assembly due to unrecoverable error: {Error}",
emitResult.Diagnostics.First(diagnostic => diagnostic.Location == Location.None && diagnostic.Severity == DiagnosticSeverity.Error));
DumpErrorDetails(emitResult.Diagnostics);
throw new CompilationException("General Build Failure detected.");
Expand Down Expand Up @@ -136,7 +136,7 @@ private CSharpCompilation RunSourceGenerators(IAnalyzerResult analyzerResult, Co
}
else
{
_logger.LogError("Failed to generate source code for mutated assembly: {0}", diagnostic);
_logger.LogError("Failed to generate source code for mutated assembly: {Diagnostics}", diagnostic);
fail = true;
}
}
Expand Down Expand Up @@ -201,7 +201,7 @@ private CSharpCompilation GetCSharpCompilation(IEnumerable<SyntaxTree> syntaxTre
null),
options: emitOptions);
}
#pragma warning disable S1696 // this catches an exception raised by the C# compiler
#pragma warning disable S1696 // this catches an exception raised by the C# compiler
catch (NullReferenceException e)
{
_logger.LogError("Roslyn C# compiler raised an NullReferenceException. This is a known Roslyn's issue that may be triggered by invalid usage of conditional access expression.");
Expand Down Expand Up @@ -234,8 +234,8 @@ private CSharpCompilation ScanForCauseOfException(CSharpCompilation compilation)
}
catch(Exception e)
{
_logger.LogError(e, "Failed to compile {0}", st.FilePath);
_logger.LogTrace("source code:\n {0}", st.GetText());
_logger.LogError(e, "Failed to compile {FilePath}", st.FilePath);
_logger.LogTrace("source code:\n {Source}", st.GetText());
syntaxTrees = syntaxTrees.Where(x => x != st).Append(_rollbackProcess.CleanUpFile(st)).ToImmutableArray();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public bool Compile(IEnumerable<ParsedInput> syntaxTrees, bool devMode)
var trees = ListModule.OfSeq(syntaxTrees.Reverse());
var dependencies = ListModule.OfSeq(analyzerResult.References);

//we need a checker if we want to compile
//we need a checker if we want to compile
var checker = FSharpChecker.Create(
projectCacheSize: null,
keepAssemblyContents: null,
Expand Down Expand Up @@ -67,7 +67,7 @@ public bool Compile(IEnumerable<ParsedInput> syntaxTrees, bool devMode)
_fileSystem.File.Copy(pdbPath, pdbInjectionpath, true);
}

_logger.LogDebug("Injected the mutated assembly file into {0}", injectionPath);
_logger.LogDebug("Injected the mutated assembly file into {InjectionPath}", injectionPath);
}

//rollback still needs to be implemented
Expand Down

0 comments on commit b5f9aa5

Please sign in to comment.