I need to pass UserId
as part of Serilog logging. For this I created a new variable UserId
with empty value in app settings, and set the value programmatically in index.razor
.
This code shown here is not working. How do I set the value for userId
in appsettings.json
?
Appsettings.json
:
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Seq",
"Args": { "serverUrl": "; }
}
],
"Properties": {
"ApplicationName": "TESTApp",
"Environment": "DEV"
"UserId": ""
}
}
index.razor
:
protected override async Task OnInitializedAsync()
{
UserName = GetUserId();
Configuration["Serilog:Properties:UserId"] = UserName;
}
I need to pass UserId
as part of Serilog logging. For this I created a new variable UserId
with empty value in app settings, and set the value programmatically in index.razor
.
This code shown here is not working. How do I set the value for userId
in appsettings.json
?
Appsettings.json
:
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Seq",
"Args": { "serverUrl": "https://logging.mysite" }
}
],
"Properties": {
"ApplicationName": "TESTApp",
"Environment": "DEV"
"UserId": ""
}
}
index.razor
:
protected override async Task OnInitializedAsync()
{
UserName = GetUserId();
Configuration["Serilog:Properties:UserId"] = UserName;
}
Share
Improve this question
edited Nov 21, 2024 at 4:48
marc_s
757k184 gold badges1.4k silver badges1.5k bronze badges
asked Nov 21, 2024 at 0:17
HenryHenry
8836 gold badges25 silver badges53 bronze badges
1
- Don't try to change the configuration, inject any extra context like stackoverflow/questions/51261177/add-username-into-serilog – Jeremy Lakeman Commented Nov 21, 2024 at 2:18
1 Answer
Reset to default 1I think you want changing the json file. You could try use "JsonObject" for easily modify the json text.
@using System.Text.Json
@using System.Text.Json.Nodes
var filePath = "appsettings.json";
var oldjson = File.ReadAllText(filePath);
var jsonobject = JsonObject.Parse(oldjson);
jsonobject["Serilog"]["Properties"]["UserId"] = UserName;
var newjson = jsonobject.ToString();
File.WriteAllText(filePath, newjson);
After the file has changed , builder.Configuration
will change automatically. Or you could make sure the configuration is reloaded when file change.
builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745547034a4632385.html
评论列表(0条)