Decoration System.Console.Out add color

I have a simple function

let OutputDebugToConsole () = new System.Diagnostics.TextWriterTraceListener(System.Console.Out) |> System.Diagnostics.Debug.Listeners.Add |> ignore 

redirect debug output from Debug.WriteLine to the console.

I want the debug output to be a different color, for example by setting Console.ForegroundColor to gray. Obviously, the color must be reset after each spelling for plain text, which should be written in standard colors. My idea is to pass another TextWriter that will decorate the Write method.

First, is this a reasonable way of thinking about a problem? Secondly, for this I will need to rewrite all the methods of my TextWriter or is there another way?

+4
source share
2 answers

Console.ForegroundColor has the getter and setter properties, so technically you can just save the old color, assign it, write and restore the old color.

However, this is not thread safe. Another thread can also use Console.Write and set its ForegroundColor property to its own preferred color. This is a race, your registrar may end up writing in a color chosen by another thread. And vice versa. There is a lock that prevents the thread from writing text to the console and displaying their output, but it's too late. There is no easy way to solve this problem, except that your logger uses pinvoke to not use ForegroundColor at all.

This is a stupid little detail if it ever was. Therefore, it is usually best to use a journal library that takes care of these unpleasant details. For example, NLog.

+5
source

You can implement this quite simply by using the Printf.kprintf function, as shown in this blog post: Color printing f

Basically, Printf.kprintf accepts a continuation to which a formatted string applies; The blog post I linked shows how you can pass on a sequel that sets the console color, prints a line, and then restores the original color before returning.

As Hans Passant wrote in his answer, there are problems with thread safety when configuring / restoring console color, so you must be sure that you will develop the application accordingly (if you use multiple threads or the F # async workflow).

+3
source

All Articles