Code Snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
open System
let ts () = DateTime.Now.ToString("o")           // ISO-8601
let cw (s:string) = Console.WriteLine(s)         // Threadsafe console writer
let cew (s:string) = Console.Error.WriteLine(s)  // Threadsafe console error writer

type LogLevel = | Info | Warning | Error

let log l x y =
  let msg = sprintf "%s - %A: %A (%A)" (ts()) l x y
  match l with
    | LogLevel.Error -> cew msg
    | LogLevel.Info | LogLevel.Warning -> cw msg

let foo x = try x/0 |> Some with ex -> log LogLevel.Error x ex; None

42 |> foo

Code output:

> val ts : unit -> string
> val cw : s:string -> unit
> val cew : s:string -> unit

> type LogLevel =
  | Info
  | Warning
  | Error

> val log : l:LogLevel -> x:'a -> y:'b -> unit

> val foo : x:int -> int option

> 2014-03-12T21:44:19.6454280+01:00 - Error: 42 (System.DivideByZeroException:
  Division by zero at FSI_0006.foo (Int32 x) [0x00000] in <filename unknown>:0 )
val it : int option = None