有的时候你有多个应用程序,它们需要使用相同的日志配置。在这种情况下,你可以将日志配置放在一个共享的位置,然后通过项目文件快速引用。方便快捷,不用重复配置。
Directory.Build.props
通过在项目文件夹中创建一个名为 Directory.Build.props
的文件,可以将配置应用于所有项目。这个文件的内容如下:
1 2 3 4 5 6 7 8 9
| <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
文件中的配置了。
1 2 3 4 5 6
| <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net7.0</TargetFramework> <MyApplication>true</MyApplication> </PropertyGroup> </Project>
|
appsettings.logging.json
在 Shared
文件夹中,我们需要创建一个名为 appsettings.logging.json
的文件,这个文件就是我们的日志配置文件。这个文件的内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| { "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
文件中的配置了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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); } }
|
文件夹结构
最后我们看一下文件夹的结构:
1 2 3 4 5 6 7 8 9
| ├───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
文件中的配置了。
参考资料
本文采用 Chat OpenAI 辅助注水浇筑而成,如有雷同,完全有可能。