Colour your Log4Net events in your RichTextBox zz

You’re most probably here because you have already read my article How to watch your log through your application in Log4Net and you’re thinking “that’s great, but I need to somehow differentiate all of this output!” – either that or you just really need a handy way to format certain keywords within your RichTextBox.

 

Either way, here’s my solution. First of all define your logging levels (or keywords) within your RichTextBox container:

Dictionary levels = new Dictionary();

should be defined somewhere within your Form class, probably at the top. This will create a container of key strings that will be your keywords, associated to particular colours that you want these keywords to be coloured within your RichTextBox. Then you need to populate it within your constructor:

// Add colours to correspond to given log levels

levels.Add("INFO", Color.Green);

levels.Add("WARN", Color.Yellow);

levels.Add("ERROR", Color.Red);

levels.Add("DEBUG", Color.Blue);

Next you need to write a function that will iterate through each of these levels/keywords, and search for each instance within your text. Once you’ve found each one you just need to select the word and set the selection colour to the colour that corresponds with that keyword:

private RichTextBox FormatLogColours(RichTextBox textbox) {

// Iterate through each level

foreach (var level in levels) {

    int pos = 0;



    // And look for every instance of it within our text

    while ((pos = textbox.Text.IndexOf(level.Key, pos)) > 0) {

        // Then select the text by getting the position and selecting from the position for the length of said level

        textbox.Select(pos, level.Key.Length);



        // And then set the corresponding colour

        textbox.SelectionColor = level.Value;



        pos++;

     }

  }



  return textbox;

}

Once you have this function defined you can essentially use it anywhere relevant. In the case of our previous article this would be write after our RichTextBox is updated by our LogWatcher event:

LogTextbox = FormatLogColours(LogTextbox);

Nice and simple! I hope this helps someone, even if it’s somewhere to start – you could easily expand it to cover all of the remaining levels, the ones used here are just the ones I used myself but there are many more or you could even expand it to the enter line by looking for the \r\n prior and after the current keyword. If you think of anything good please feel free to add a link in the comments below!

你可能感兴趣的:(event)