2

I want to add a method to the existing LoggerExtensions on Core 2.1 that will need to use IConfiguration to read some settings from the appsettings.json file.

I created a partial static class with my new method inside it but this does not allow me to access the IConfiguration as it is a static class.

How could I create this new method that is part of LoggerExtensions that can read from IConfiguration?

In the example below I can't access _configuration.GetSection as I can not inject it

public static partial class LoggerExtensions { public static void EmailError(this ILogger logger, Exception exception, string message) { using (var smtpClient = new SmtpClient(config.GetSection("Host").Value)) { // ...... } } } 
1
  • Add some code that what you have tried so far! Commented Jan 8, 2019 at 15:31

1 Answer 1

3

You should add the IConfiguration instance as a parameter to the extension method. For example:

public static void LogErrorAndEmail(this ILogger logger, IConfiguration configuration, Exception exception, string message, params object[] args) { // ... } 

A better option might be to create a custom logger implementation which sends a mail under specific conditions. You can start by implementing the ILogger interface and implement your mail logic in the Log method. Inject the IConfiguration instance in the constructor. Secondly create a ILoggerFactory implementation to create a new instance of your custom logger, inject the IConfigruation parameter in the constructor as well and pass it to your logger. Finally call services.AddSingleton<ILoggerProvider, YourCustomLoggerProvider>() in the startup class to register your custom logger.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.