0

I have a solution with multiple projects. And I want to set Logger in SDK/common class library and use serilog logger in other projects.

Each project generates log files with different settings. The question is: Since the IConfiguration passed to Serilog-static-Logger is also statically typed, each project has its own appsettings, will there be conflicts? How will serilog handle it? Should I use ILogger for each project?

e.g. project 1 is writing to its log, and project 2 starts running and sets the static IConfiguration.

This is what I have in SDK:

using Microsoft.Extensions.Configuration;
using Serilog;

namespace MyProject.SDK.Logger
{
    public static class Logger
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        public static bool SetLogger()
        {
            try
            {
                Serilog.Log.Logger = new LoggerConfiguration()
                            .ReadFrom.Configuration(Configuration)
                            .CreateLogger();
                return true;
            }
            catch (Exception ex)
            {
                Serilog.Log.Logger = new LoggerConfiguration()
                            .ReadFrom.Configuration(Configuration)
                            .Enrich.FromLogContext()
                            .CreateLogger();
                Serilog.Log.Error("Exception while setting logging: " + ex.Message);
                return false;
            }
        }
    }
}

This is the appsettings in one project:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Verbose",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log_.txt",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
          "rollinginterval": "Day",
          "retainedFileCountLimit": "30",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 2097152
        }
      }
    ]
  }
}

I expect: after setting the logger, the logger can be used in all the other projects in the same solution and each project generate their log files simultaneously.

benjitino
  • 1
  • 1

0 Answers0