.Net Core Serilog AppSettings Dependancy Injection With WPF

madaxe2020

Well-known member
Joined
Sep 7, 2020
Messages
50
Programming Experience
5-10
Evening All,

My logs wont write to file, if I uncomment '.WriteTo.File("log.txt")' then I get a log file, but I really want the appsettings to manage the configration. Can anybody see why its not writting the log files

Thanks in Advance

Madaxe


App.XAML.cs:
public partial class App : Application
    {

        private void OnStartup(object sender, StartupEventArgs e)
        {
            IConfigurationBuilder builder = new ConfigurationBuilder();
            BuildConfig(builder);

            ILogger logger = new LoggerConfiguration()
                .ReadFrom.Configuration(builder.Build())
                .Enrich.FromLogContext()
                //.WriteTo.Console()
                //.WriteTo.File("log.txt")
                .CreateLogger();

            logger.Information("Application Starting");

            var host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    services.AddSingleton<MainWindow>();
                    services.AddSingleton<RootViewModel>();
                    services.AddSingleton(logger);
                })
                .UseSerilog()
                .Build();

            MainWindow mainWindow = ActivatorUtilities.CreateInstance<MainWindow>(host.Services);
            mainWindow.DataContext = ActivatorUtilities.CreateInstance<RootViewModel>(host.Services);
            mainWindow.Show();
        }

        private static void BuildConfig(IConfigurationBuilder builder)
        {
            builder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .AddEnvironmentVariables();
        }
    }
}

RootViewModel:
public interface IRootViewModel
    {

    }
    public class RootViewModel
    {
        private ILogger _logger;
        public RootViewModel(ILogger logger)
        {
            _logger = logger;
            _logger.Information("Writing to log file with INFORMATION severity level.");
            _logger.Debug("Writing to log file with DEBUG severity level.");
            _logger.Warning("Writing to log file with WARNING severity level.");
            _logger.Error("Writing to log file with ERROR severity level.");
            _logger.Fatal("Writing to log file with CRITICAL severity level.");
        }
    }

appsettings.json:
{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/cp_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Information' or @Level = 'Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/cp_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }
}
 
Solution
I ended up talking with Serilog through Github, they changed the filtering syntax to a short expression i.e. '@Level' is not just '@l' once i changed that it magically worked.

Working appsettings.json 12302021:
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByExcluding",
                "Args": {
                  "expression": "(@l='Error' or @l='Fatal' or @l='Warning')"
                }
              }
            ]...
I don't use SeriLog, so these questions may sound naive:

Does SeriLog create folders if needed when the log file path includes them? Does the app have enough rights to create folders?

In your configuration, you seem to want the log file in a "Logs" folder. Does the folder exist (if SeriLog doesn't create necessary folders)? Does the app have enough rights to create and update files in that folder?
 
Morning, Even if I Create the Logs folder and run in Admin mode it still does not work.
Thanks for the suggestions

Madaxe
 
So if i use these appsettings then it works, so there must be something in the more complex version that is causing it to fail even the sample one from Serilog fails.

Working AppSettings:
{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": ".\\Logs\\log.txt",
          "rollingInterval": "Day"
        }
      }
    ]
  }
}
 
so the problem is happening when I try to split the logging into two separate files of log levels. Does anybody know why?

Writes to Log:
{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": ".\\Logs\\ex_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
,
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }
}


Fails to Write to Log:
{
 
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": ".\\Logs\\ex_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Information' or @Level = 'Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": ".\\Logs\\cp_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }
}
 
Can you change the logger names to be different? Or do they have to be the same? (As I said, I don't use Serilog, so I don't know what it architecture or usage paradigm is supposed to be like.)
 
I ended up talking with Serilog through Github, they changed the filtering syntax to a short expression i.e. '@Level' is not just '@l' once i changed that it magically worked.

Working appsettings.json 12302021:
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByExcluding",
                "Args": {
                  "expression": "(@l='Error' or @l='Fatal' or @l='Warning')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": ".\\Logs\\cp_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByExcluding",
                "Args": {
                  "expression": "(@l='Information' or @l='Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": ".\\Logs\\ap_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }
}
 
Solution

Latest posts

Back
Top Bottom