我正在尝试将API管理网关的请求和响应记录到Azure事件中心。为此,我使用“日志到事件中心”策略。我想向包含以下内容的事件中心发送单个事件请求和响应都在一起。
我尝试将event-hub策略包含在入站策略中,同时将请求和响应都包含在内,但我仅获得请求而不是响应。同样,我尝试将其包含在出站策略中,但仅获得响应。当我将事件中心日志发送到Azure Log Analytics时,我希望将完整的请求和响应放在一起。我知道在入站和出站策略中都保留“ log-to-event-hub”策略会给我两个不同的日志事件。
<inbound>
<set-variable name="message-id" value="@(Guid.NewGuid())" />
<log-to-eventhub logger-id="all-logs" partition-id="0">@{
var requestLine = string.Format("{0} {1} HTTP/1.1\r\n",
context.Request.Method,
context.Request.Url.Path + context.Request.Url.QueryString);
var body = "Request " + context.Request.Body?.As<string>(true) + "Response " + context.Response.Body?.As<string>(true);
var headers = context.Request.Headers
.Where(h => h.Key != "Authorization" && h.Key != "Ocp-Apim-Subscription-Key")
.Select(h => string.Format("{0}: {1}", h.Key, String.Join(", ", h.Value)))
.ToArray<string>();
var headerString = (headers.Any()) ? string.Join("\r\n", headers) + "\r\n" : string.Empty;
return "staging: " + context.Response.StatusCode + " " + context.Variables["message-id"] + "\n"
+ requestLine + headerString + "\r\n" + body;
}</log-to-eventhub>
</inbound>
是否有可能在同一事件中同时发生这两个事件,并且仅记录了一个事件?
答案 0 :(得分:4)
我将从变量中的请求中捕获所需的值,将其与出站策略中的请求值组合在一起并记录在其中:
<policies>
<inbound>
<base />
<set-variable name="requestHeaders" value="@(JsonConvert.SerializeObject(context.Request.Headers))" />
<set-variable name="requestBody" value="@(context.Request.Body.As<string>(true))" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<log-to-eventhub logger-id="testlogger">@{
var content = new JObject();
content["reqHeaders"] = context.Variables.GetValueOrDefault<string>("requestHeaders");
content["reqBody"] = context.Variables.GetValueOrDefault<string>("requestBody");
content["resStatus"] = JsonConvert.SerializeObject(context.Response.StatusCode);
content["resBody"] = context.Response.Body.As<string>(true);
return content.ToString();
}</log-to-eventhub>
</outbound>
<on-error>
<base />
</on-error>
</policies>