-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.mbt
More file actions
155 lines (149 loc) · 4.79 KB
/
Copy pathlogging.mbt
File metadata and controls
155 lines (149 loc) · 4.79 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
///|
/// A structured access-log record (← go-zero's `logx` HTTP access fields). Rather
/// than a free-form line, each request is captured as typed fields and rendered
/// as one JSON object per line — the format go-zero emits under `logx` and the
/// shape log collectors (ELK, Loki) expect.
pub(all) struct RequestLog {
http_method : String
path : String
status : Int
duration_ms : Int64
request_id : String
client_ip : String
user_agent : String
}
///|
/// The record as a JSON value with a stable field order, `duration_ms` rendered
/// as a number of milliseconds.
pub fn RequestLog::to_json(self : RequestLog) -> Json {
Json::object(
Map([
("method", Json::string(self.http_method)),
("path", Json::string(self.path)),
("status", Json::number(self.status.to_double())),
("duration_ms", Json::number(self.duration_ms.to_double())),
("request_id", Json::string(self.request_id)),
("client_ip", Json::string(self.client_ip)),
("user_agent", Json::string(self.user_agent)),
]),
)
}
///|
/// The record rendered as a single-line JSON string, ready to write to a log
/// sink.
pub fn RequestLog::render(self : RequestLog) -> String {
self.to_json().stringify()
}
///|
/// The record as `logx` fields, for logging it through a `Logger` — the method
/// and path make the entry's message, so they are not repeated here.
pub fn RequestLog::fields(self : RequestLog) -> Array[(String, Json)] {
[
("status", Json::number(self.status.to_double())),
("duration_ms", Json::number(self.duration_ms.to_double())),
("request_id", Json::string(self.request_id)),
("client_ip", Json::string(self.client_ip)),
("user_agent", Json::string(self.user_agent)),
]
}
///|
/// The client IP from an HTTP scope: the `X-Forwarded-For` first hop if present
/// (proxy-aware, as go-zero's `httpx.GetRemoteAddr`), else the transport peer
/// from the scope's `client`, else `"-"`.
fn client_ip_of(scope : @moonasgi.Scope) -> String {
match scope {
Http(hs) => {
for pair in hs.headers {
if pair.0.to_lower() == "x-forwarded-for" {
let raw = pair.1
let mut end = 0
while end < raw.length() && raw[end] != ',' {
end = end + 1
}
return raw[0:end].to_owned()
}
}
match hs.client {
Some((ip, _)) => ip
None => "-"
}
}
_ => "-"
}
}
///|
/// A request header's value from an HTTP scope, matched case-insensitively;
/// `default` when absent or on a non-HTTP scope.
fn header_ci(
scope : @moonasgi.Scope,
name : String,
default : String,
) -> String {
match scope {
Http(hs) => {
for pair in hs.headers {
if pair.0.to_lower() == name {
return pair.1
}
}
default
}
_ => default
}
}
///|
/// Structured-logging middleware (← go-zero's `LogHandler`): time each HTTP
/// request on the shared clock, capture its method/path/client-ip/user-agent and
/// the response status observed on `HttpResponseStart`, and write one access
/// entry through `logger` (the process `logx` by default) when the response
/// starts. Access logs are `info`, so a service configured at `error` or above
/// emits none of them. Non-HTTP scopes pass through without logging.
pub fn structured_logging(clock : Clock, logger? : Logger) -> Middleware {
let lg = logger.unwrap_or(logx)
inner => {
(scope, receive, send) => {
match scope {
Http(hs) => {
let start = clock.now()
let verb = hs.http_method
let path = hs.path
let ip = client_ip_of(scope)
let ua = header_ci(scope, "user-agent", "-")
let rid = header_ci(scope, "x-request-id", "-")
let logged : Ref[Bool] = { val: false, }
let observed : @moonasgi.Send = event => {
match event {
HttpResponseStart(status~, headers~, trailers~) => {
if !logged.val {
logged.val = true
let entry = RequestLog::{
http_method: verb,
path,
status,
duration_ms: clock.now() - start,
request_id: rid,
client_ip: ip,
user_agent: ua,
}
lg
.with_duration(entry.duration_ms)
.info(verb + " " + path, fields=entry.fields())
}
send(
@moonasgi.Event::HttpResponseStart(
status~,
headers~,
trailers~,
),
)
}
other => send(other)
}
}
inner(scope, receive, observed)
}
_ => inner(scope, receive, send)
}
}
}
}