Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gray out logging code using ReSharper

Is it possible to use ReSharper to gray out useful but bloaty code using ReSharper? For example, when I want to add verbose logging it would be good to make the functional code stand out around the logging code.

I have tried using ReSharper's Pattern Catalog search to match patterns in my code and highlight them in gray but it only supports Hints, Suggestions, Warnings and Errors.

I'm looking for something similar to how Debug.WriteLine is displayed in Release mode, although I don't want to code to be compiled out.

like image 723
Jason Allen Avatar asked Jun 08 '13 13:06

Jason Allen


1 Answers

You can sort-of achieve this, but it's kind of a hack. What you could do, is decorate your logging methods with the ConditionalAttribute, using ReSharper's External Annotations.

Annotations are used in ReSharper almost everywhere, it's how it knows to gray out the Debug.WriteLine line in Release, for example, since the Debug.Write... lines are decorated with [Conditional("DEBUG")] attribute.

What you could do is cheat by making ReSharper think that such a conditional method exists on your logger's methods. You can do it by applying this attribute externally via XML.

I wrote about doing something like this in my blog, here's how you could do this:

  1. Create a file called YourLogger.ExternalAnnotations.xml, e.g. NLog.ExternalAnnotations.xml and place it next to your logger assembly.
  2. Add the following:
<assembly name="NLog">
  <member name="M:NLog.Logger.Info(System.String)">
    <attribute ctor="M:System.Diagnostics.ConditionalAttribute.#ctor(System.String)">
      <argument>LOG</argument>
    </attribute>
  </member>
  <member name="M:NLog.Logger.Debug(System.String)">
    <attribute ctor="M:System.Diagnostics.ConditionalAttribute.#ctor(System.String)">
      <argument>LOG</argument>
    </attribute>
  </member>
</assembly>

For each method you wish to "gray out", you will need to add a <member> block with the XML-Doc ID name of the method. In ReSharper 8 EAP there's an option Copy XML-Doc ID to Clipboard, located under ReSharper's Edit menu.

This essentially causes ReSharper's engine to think there's a [Conditional("LOG")] defined in the logger's type metadata.

After you've added all the desired methods, simply reload the solution. You should get what you are looking for (sort of... like I said, it's a hack :))

ReSharper hackery

like image 155
Igal Tabachnik Avatar answered Nov 17 '22 01:11

Igal Tabachnik