如何在多个应用程序中共享日志配置

发布时间 2023-03-22 19:08:09作者: Newbe36524

有的时候你有多个应用程序,它们需要使用相同的日志配置。在这种情况下,你可以将日志配置放在一个共享的位置,然后通过项目文件快速引用。方便快捷,不用重复配置。

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