2

In ASP.NET Core 2.2 I used to be able to log exception errors in startup by using DI, but now on 3.1

   public class Startup
   {
        public Startup(IConfiguration configuration, ILogger<Startup> logger)
        {
            Configuration = configuration;
            _logger = logger;
        }

        public IConfiguration Configuration { get; }

        private readonly ILogger<Startup> _logger;
        ....

but now an exception appears when I run my app:

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[TestProject.Startup]' while attempting to activate 'TestProject.Startup'.

My logging is configured for the ones who are asking in the Program

    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .WriteTo.File(@"Logging\log.txt",
               fileSizeLimitBytes: 10_000,
               rollOnFileSizeLimit: true,
               shared: true,
               flushToDiskInterval: TimeSpan.FromSeconds(1))
            .CreateLogger();

            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally

            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

SOLUTION

I found the solution in this thread and my problem is solved:

How do I write logs from within Startup.cs

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jackal
  • 3,359
  • 4
  • 33
  • 78
  • Does this https://stackoverflow.com/questions/52921966/unable-to-resolve-ilogger-from-microsoft-extensions-logging solve your issue? – Athanasios Kataras Jan 08 '20 at 11:47
  • The obvious reason is that your code hasn't configured either logging or DI yet. Those methods are part of the `Startup` class and are called *after* the constructor. – Panagiotis Kanavos Jan 08 '20 at 11:48
  • Thanks, i have found the solution and i edited my post with more details and the solution – Jackal Jan 08 '20 at 11:52
  • 2
    Does this answer your question? [How do I write logs from within Startup.cs](https://stackoverflow.com/questions/41287648/how-do-i-write-logs-from-within-startup-cs) – Maximilian Ast Jan 08 '20 at 11:58
  • @MaximilianAst check my post at the end, i posted the solution – Jackal Jan 08 '20 at 12:12
  • 1
    Yea there I copied it from, When you flag a question as duplicate it posts this comment automatically – Maximilian Ast Jan 08 '20 at 12:24

0 Answers0