有的時候你有多個應用程序,它們需要使用相同的日誌配置。在這種情況下,你可以將日誌配置放在一個共享的位置,然後通過項目文件快速引用。方便快捷,不用重複配置。
Directory.Build.props
通過在項目文件夾中創建一個名爲 Directory.Build.props
的文件,可以將配置應用於所有項目。這個文件的內容如下:
<Project>
<ItemGroup Condition="$(MyApplication) == 'true'">
<Content Include="..\Shared\appsettings.logging.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Link>Shared\appsettings.logging.json</Link>
</Content>
</ItemGroup>
</Project>
我們可以將這個文件放在解決方案文件夾的根目錄中,這樣就可以將配置應用於所有項目。
由於我們定義了一個條件,所以我們可以通過設置 MyApplication
屬性來控制是否應用這個配置。在這個例子中,我們將 MyApplication
屬性設置爲 true
,所以我們只要在項目文件中設置這個屬性,就可以應用這個配置。
項目文件
在項目文件中,我們需要設置 MyApplication
屬性,然後引用 Directory.Build.props
文件。這樣就可以應用 Directory.Build.props
文件中的配置了。
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<MyApplication>true</MyApplication>
</PropertyGroup>
</Project>
appsettings.logging.json
在 Shared
文件夾中,我們需要創建一個名爲 appsettings.logging.json
的文件,這個文件就是我們的日誌配置文件。這個文件的內容如下:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
}
使用 appsettings.logging.json
在 Program.cs
文件中,我們需要將日誌配置文件的路徑傳遞給 CreateHostBuilder
方法。這樣就可以使用 appsettings.logging.json
文件中的配置了。
private void LoadSharedAppSettings(WebApplicationBuilder builder)
{
var appsettingsParts = new[] { "logging" };
var sharedBaseDir = Path.Combine(AppContext.BaseDirectory, "Shared");
foreach (var appsettingsPart in appsettingsParts)
{
builder.Configuration.AddJsonFile(Path.Combine(sharedBaseDir, $"appsettings.{appsettingsPart}.json"),
true, true);
builder.Configuration.AddJsonFile(
Path.Combine(sharedBaseDir,
$"appsettings.{appsettingsPart}.{builder.Environment.EnvironmentName}.json"),
true, true);
}
}
文件夾結構
最後我們看一下文件夾的結構:
├───MyApplication1
│ ├───Properties
│ └───wwwroot
├───MyApplication2
│ ├───Properties
│ └───wwwroot
├───Shared
│ └───appsettings.logging.json
└───MyApplication.sln
總結
通過在項目文件夾中創建一個名爲 Directory.Build.props
的文件,可以將配置應用於所有項目。在項目文件中,我們需要設置 MyApplication
屬性,然後引用 Directory.Build.props
文件。在 Program.cs
文件中,我們需要將日誌配置文件的路徑傳遞給 CreateHostBuilder
方法。這樣就可以使用 appsettings.logging.json
文件中的配置了。
參考資料
- Directory.Build.props[1]
- appsettings.json[2]
- 本文作者: newbe36524
- 本文鏈接: https://www.newbe.pro/ChatAI/0x015-How-to-share-logging-configuration-in-multiple-applications/
- 版權聲明: 本博客所有文章除特別聲明外,均採用 BY-NC-SA 許可協議。轉載請註明出處!
參考資料
[1]Directory.Build.props: https://learn.microsoft.com/visualstudio/msbuild/customize-your-build?view=vs-2022&WT.mc_id=DX-MVP-5003606#directorybuildprops-and-directorybuildtargets
[2]appsettings.json: https://learn.microsoft.com/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0&WT.mc_id=DX-MVP-5003606#appsettingsjson