9 people like it.

Super-simple, thread safe, colored console output

Write colored console messages, without them getting intermingled if writing from parallel/async processes.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
module Console =

    open System

    let log =
        let lockObj = obj()
        fun color s ->
            lock lockObj (fun _ ->
                Console.ForegroundColor <- color
                printfn "%s" s
                Console.ResetColor())

    let complete = log ConsoleColor.Magenta
    let ok = log ConsoleColor.Green
    let info = log ConsoleColor.Cyan
    let warn = log ConsoleColor.Yellow
    let error = log ConsoleColor.Red

module Main =

    let demo() = 
        let fileName = "myfile.txt"
        Console.info <| sprintf "Opening file %s" fileName
namespace System
val log : (ConsoleColor -> string -> unit)

Full name: Script.Console.log
val lockObj : Object
type obj = Object

Full name: Microsoft.FSharp.Core.obj
val color : ConsoleColor
val s : string
val lock : lockObject:'Lock -> action:(unit -> 'T) -> 'T (requires reference type)

Full name: Microsoft.FSharp.Core.Operators.lock
type Console =
  static member BackgroundColor : ConsoleColor with get, set
  static member Beep : unit -> unit + 1 overload
  static member BufferHeight : int with get, set
  static member BufferWidth : int with get, set
  static member CapsLock : bool
  static member Clear : unit -> unit
  static member CursorLeft : int with get, set
  static member CursorSize : int with get, set
  static member CursorTop : int with get, set
  static member CursorVisible : bool with get, set
  ...

Full name: System.Console
property Console.ForegroundColor: ConsoleColor
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Console.ResetColor() : unit
val complete : (string -> unit)

Full name: Script.Console.complete
type ConsoleColor =
  | Black = 0
  | DarkBlue = 1
  | DarkGreen = 2
  | DarkCyan = 3
  | DarkRed = 4
  | DarkMagenta = 5
  | DarkYellow = 6
  | Gray = 7
  | DarkGray = 8
  | Blue = 9
  ...

Full name: System.ConsoleColor
field ConsoleColor.Magenta = 13
val ok : (string -> unit)

Full name: Script.Console.ok
field ConsoleColor.Green = 10
val info : (string -> unit)

Full name: Script.Console.info
field ConsoleColor.Cyan = 11
val warn : (string -> unit)

Full name: Script.Console.warn
field ConsoleColor.Yellow = 14
val error : (string -> unit)

Full name: Script.Console.error
field ConsoleColor.Red = 12
module Main

from Script
val demo : unit -> unit

Full name: Script.Main.demo
val fileName : string
module Console

from Script
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf

More information

Link:http://fssnip.net/7Vy
Posted:5 years ago
Author:Kit Eason
Tags: #console , #threading