So I'm trying to log out some additional information to every, single logging call. Basically stuff like the environment and machine names.
I've got my logging set up like this:
builder.Logging.AddJsonConsole(b =>
{
b.IncludeScopes = true;
b.TimestampFormat = "[dd-MM-yy -- HH:mm:ss]";
});
And I set up a bit of middleware that I thought would do the trick:
app.Use(async (c, n) =>
{
var logger = c.RequestServices.GetRequiredService<ILogger<Program>>();
using (logger.BeginScope("{EnvironmentName}", "myEnvironment"))
{
await n();
}
});
However, this doesn't actually seem to be appending the new field to all of my logs - it comes up on manual calls to Logger.LogX()
but not anything generated by Hosting.Diagnostics
:
{
"Timestamp": "[18-01-22 -- 10:42:41]",
"EventId": 2,
"LogLevel": "Information",
"Category": "Microsoft.AspNetCore.Hosting.Diagnostics",
"Message": "Request finished HTTP/1.1 GET http://localhost:29965/ - - - 404 0 - 462.7596ms",
"State": {
"Message": "Request finished HTTP/1.1 GET http://localhost:29965/ - - - 404 0 - 462.7596ms",
"ElapsedMilliseconds": 462.7596,
"StatusCode": 404,
"ContentType": null,
"ContentLength": 0,
"Protocol": "HTTP/1.1",
"Method": "GET",
"Scheme": "http",
"Host": "localhost:29965",
"PathBase": "",
"Path": "/",
"QueryString": ""
},
"Scopes": [
{
"Message": "SpanId:d592c9c95a00b532, TraceId:9a3c107a9f7d5a5422692f5bdaf6cf56, ParentId:0000000000000000",
"SpanId": "d592c9c95a00b532",
"TraceId": "9a3c107a9f7d5a5422692f5bdaf6cf56",
"ParentId": "0000000000000000"
},
{
"Message": "ConnectionId:0HMEQDT08VU1Q",
"ConnectionId": "0HMEQDT08VU1Q"
},
{
"Message": "RequestPath:/ RequestId:0HMEQDT08VU1Q:00000002",
"RequestId": "0HMEQDT08VU1Q:00000002",
"RequestPath": "/"
}
]
}
{
"Timestamp": "[18-01-22 -- 10:57:27]",
"EventId": 1,
"LogLevel": "Information",
"Category": "Microsoft.AspNetCore.Routing.EndpointMiddleware",
"Message": "Executed endpoint 'HTTP: GET subscriptioninfo/api/alive-test'",
"State": {
"Message": "Executed endpoint 'HTTP: GET subscriptioninfo/api/alive-test'",
"EndpointName": "HTTP: GET subscriptioninfo/api/alive-test",
"{OriginalFormat}": "Executed endpoint '{EndpointName}'"
},
"Scopes": [
{
"Message": "SpanId:8aa7c06a93c883d6, TraceId:efc7d6f4907471d88077e7b4eaba4295, ParentId:0000000000000000",
"SpanId": "8aa7c06a93c883d6",
"TraceId": "efc7d6f4907471d88077e7b4eaba4295",
"ParentId": "0000000000000000"
},
{
"Message": "ConnectionId:0HMEQE57CSO2D",
"ConnectionId": "0HMEQE57CSO2D"
},
{
"Message": "RequestPath:/subscriptioninfo/api/alive-test RequestId:0HMEQE57CSO2D:00000002",
"RequestId": "0HMEQE57CSO2D:00000002",
"RequestPath": "/subscriptioninfo/api/alive-test"
},
{
"Message": "myEnvironment",
"EnvironmentName": "myEnvironment",
"{OriginalFormat}": "{EnvironmentName}"
}
]
}
I feel like adding some default fields to a request should be easy. It's easy to do with Serilog and NLog. So how do I achieve this without using a separate logging framework?