sonarqube-roslyn-sdk icon indicating copy to clipboard operation
sonarqube-roslyn-sdk copied to clipboard

How to implement logging in custom rules created by sonarqube-roslyn-sdk

Open naveenkumarmca opened this issue 5 years ago • 3 comments

I have to implement logging in the custom rules plugin developed for C# using sonarqube-roslyn-sdk . Default log I have attached here. I have tried following 2 Console.WriteLine("Initialize method is started"); Trace.WriteLine("Initialize method is started"); But there did not come up on logs/console.

We need to add some more details in log. How to implement ? Can you please help on this . Thanks in advance.

image

naveenkumarmca avatar Aug 07 '19 11:08 naveenkumarmca

Hi @naveenkumarmca, The logs in your screen shot are from the Scanner end step so they definitely won't contain any output from your Roslyn rules, since the Roslyn analyzers are run during the MSBuild step by the C# compiler and will already have been executed.

More specifically, writing additional output from Roslyn analyzers has nothing to do with the sonarqube-roslyn-sdk; you can ignore it completely for the purposes of working out how to emit additional output during the build phase.

I don't think that the Roslyn framework provides a specific method to log additional output. However, I would expect that using Trace.WriteLine would work as long as you have an appropriate TraceListener registered - I wouldn't expect the Trace output to be captured by default.

duncanp-sonar avatar Aug 07 '19 14:08 duncanp-sonar

Hi @duncanp-sonar , Screen shot is attached as an example. In that case can we implement the logging in scanner start/ rebuild steps ?

naveenkumarmca avatar Aug 08 '19 04:08 naveenkumarmca

Hi @duncanp-sonar , Added the following code. But still it is not coming in logs. Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.AutoFlush = true; Trace.Indent(); Trace.WriteLine("Initialize method is started"); Trace.Unindent();

naveenkumarmca avatar Aug 08 '19 12:08 naveenkumarmca

Hi @naveenkumarmca,

Roslyn analyzers do not provide any way how you can emit logs during your build. And the plugin generated by this SDK also does not provide any direct API to achieve that.

The only viable option I see is to build a custom SonarQube plugin, without the SDK - that means building maven Java project:

  • Update your plugin to write your output somewhere to disk, where it will be later picked up by your custom Plugin. The tricky part will be to define a suitable location that is known to both systems (Roslyn analyzer and Java plugin).
  • Clone https://github.com/SonarSource/sonarqube-roslyn-sdk-template-plugin
  • Update the source code to:
    • Read the logs from the file you've produced and emit them to output logs
    • Build the JAR
  • Extract XML and static resources from SDK-generated file and update your custom JAR to plug in your own analyzer