我有一个单独的微服务,它从另一个微服务获取 HTTP 消息(JSON),使用 Serilog 记录它们(消息)并将它们发送到 graylog(GELF)。一条消息 - 一条日志,例如:
- 消息:“请求开始 HTTP/1.1 GET http://localhost:44312/api/home” 来自:“WebApplication,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null” 2)消息:“记录示例文本消息! !!” 来自:“WebApplication,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null” ....
我想为从其他微服务发送的每条消息添加一个“请求 ID”字段,而不在其他微服务中使用 Serilog。如何在 MyLogger 类中获取它?
第一条和第二条消息 - 是相同的请求,但我的“logging-microservce”将它们作为两个不同的消息获取,并且该服务内的 serilog((“logging-microservce”)将它们作为具有不同请求 ID 的另外两个请求处理。
public class MyLogger : ILogger
{
public MyLogger()
{
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var message = formatter(state, exception);
if (exception != null)
{
message = $"{exception.GetType()}: {exception.Message}";
}
var logMessageModel = new LogMessageModel(logLevel, message, **REQUEST_ID???????,** Assembly.GetEntryAssembly().FullName, exception?.StackTrace);
string selectionString = JsonConvert.SerializeObject(logMessageModel);
using (var client = new HttpClient())
{
StringContent stringContent = new StringContent(selectionString, Encoding.UTF8, "application/json");
client.PostAsync($"https://localhost:44353/api/logging", stringContent).GetAwaiter().GetResult();
}
}
}
我的日志服务中的 Serilog 配置:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Graylog", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Error",
"Override": {
"LoggingExample.Handler": "Information"
}
},
"WriteTo": [
{
"Name": "Graylog",
"Args": {
"hostnameOrAddress": "127.0.0.1",
"port": "1514",
"transportType": "Tcp"
}
}
],
"Properties": {
"Application": "Centralized logging application"
}
},
"AllowedHosts": "*"
}
.NET 核心 2.2