Source file breadcrumb.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
open Core_kernel

type level =
  [ `Critical
  | `Error
  | `Warning
  | `Info
  | `Debug
  ]
[@@deriving sexp_of]

let level_to_string = function
  | `Critical -> "critical"
  | `Error -> "error"
  | `Warning -> "warning"
  | `Info -> "info"
  | `Debug -> "debug"
;;

type t =
  { timestamp : Time.t sexp_opaque
  ; type_ : string
  ; message : string option
  ; data : Json.t String.Map.t
  ; category : string option
  ; level : level
  }
[@@deriving sexp_of]

let make
    ?timestamp
    ?(type_ = "default")
    ?message
    ?(data = String.Map.empty)
    ?category
    ?(level = `Info)
    ()
  =
  let timestamp =
    match timestamp with
    | Some timestamp -> timestamp
    | None -> Time.now ()
  in
  { timestamp; type_; message; data; category; level }
;;

let make_navigation ?timestamp ?message ?category ?level ~from ~to_ () =
  let data = [ "from", `String from; "to", `String to_ ] |> String.Map.of_alist_exn in
  make ?timestamp ?message ?category ?level ~data ~type_:"navigation" ()
;;

let make_http ?timestamp ?message ?category ?level ~url ~method_ ~status_code ~reason () =
  let data =
    [ "url", `String url
    ; "method", `String method_
    ; "status_code", `Int status_code
    ; "reason", `String reason
    ]
    |> String.Map.of_alist_exn
  in
  make ?timestamp ?message ?category ?level ~data ~type_:"http" ()
;;

let to_payload t =
  { Payloads_t.timestamp = t.timestamp
  ; type_ = Some t.type_
  ; message = t.message
  ; data = Util.map_to_alist_option t.data
  ; category = t.category
  ; level = Some (level_to_string t.level)
  }
;;

let%test_module _ =
  (module struct
    let timestamp = Time.of_string "2018-09-12T12:09:02Z"

    let%expect_test "empty to_payload" =
      make ~timestamp () |> to_payload |> Payloads_j.string_of_breadcrumb |> print_endline;
      [%expect
        {| {"timestamp":"2018-09-12T12:09:02.000000","type":"default","level":"info"} |}]
    ;;

    let%expect_test "navigation to_payload" =
      make_navigation ~timestamp ~from:"example from" ~to_:"example to" ()
      |> to_payload
      |> Payloads_j.string_of_breadcrumb
      |> print_endline;
      [%expect
        {| {"timestamp":"2018-09-12T12:09:02.000000","type":"navigation","data":{"from":"example from","to":"example to"},"level":"info"} |}]
    ;;

    let%expect_test "http to_payload" =
      make_navigation ~timestamp ~from:"example from" ~to_:"example to" ()
      |> to_payload
      |> Payloads_j.string_of_breadcrumb
      |> print_endline;
      [%expect
        {| {"timestamp":"2018-09-12T12:09:02.000000","type":"navigation","data":{"from":"example from","to":"example to"},"level":"info"} |}]
    ;;
  end)
;;