Search code examples
asp.net-corebackgroundworker

How to save log in file in .net core worker service?


nowadays, I am working on a .Net core worker service and I'd like to save my project's errors in a file (text file) I couldn't find any settings for this

.ConfigureLogging((hostingContext, logging) =>
{ 
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));

    logging.AddEventLog(new EventLogSettings()
    {
        SourceName = "CallerTestCacheServiceCoreAPI",
        LogName = "CallerTestCacheServiceCoreAPILog",                     
    });
})


Solution

  • I added an extension method in another class like this project https://github.com/MV10/Serilog.Dependency.Injection

    public static IServiceCollection AddSerilogServices(this IServiceCollection services)
    {
        return services.AddSerilogServices(
            new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.File("log.txt")
                //.WriteTo.File(new CompactJsonFormatter(), "log.txt")
                .WriteTo.Console());
    }
    

    and introduce it in program.cs services

    services.AddSerilogServices();
    

    and in my worker class:

    readonly Serilog.ILogger _log;
    
    public Worker(  Serilog.ILogger log)
    {  
        _log = log;
        log.Information("Hello World!");  
    }
    

    and it worked