我有一个控制台应用程序,我想使用 Serilog (v2.12.0) http 接收器 (v8.0.0) 登录到 Logtail,并为身份验证承载配置自定义 httpclient,如下所示:
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Sinks.Http;
internal class Program
{
private static void Main(string[] args)
{
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
ILogger Log = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Http(
requestUri: "https://in.logtail.com/",
queueLimitBytes: null,
httpClient: new CustomHttpClient()
)
.CreateLogger()
.ForContext<Program>();
Log.Information("log message in json format");
}
}
public class CustomHttpClient : IHttpClient
{
private readonly HttpClient httpClient;
public CustomHttpClient() => httpClient = new HttpClient();
public void Configure(IConfiguration configuration) =>
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "bearer token");
public async Task<HttpResponseMessage> PostAsync(string requestUri, Stream contentStream)
{
var content = new StreamContent(contentStream);
content.Headers.Add("Content-Type", "application/json");
var response = await httpClient
.PostAsync(requestUri, content)
.ConfigureAwait(false);
return response;
}
public void Dispose() => httpClient?.Dispose();
}
到目前为止它不起作用,但如果我在 Postman 中使用 json 格式的日志消息,它就可以工作。 以下是 Logtail 对 http 源码的说明:
内容的结构应符合您特定 URL 的 POST 事件的要求。 https://in.logtail.com/.
//样品 var content = new StreamContent(contentStream);
var jsonData = new StreamReader(contentStream).ReadToEnd();
// 示例:要检查使用您为邮递员发布的相同数据
var newJson = // JSON 数据的结构应符合您特定 URL 的 POST 事件的要求。
var content = new StringContent(newJson, Encoding.UTF8, "application/json");
var 响应 = 等待 httpClient .PostAsync(requestUri, 内容) .ConfigureAwait(假);
返回响应;
这应该有效