1

I am using .Net 6 Web Api application using C# and wanted to write logs only to console if ASPNETCORE_ENVIRONMENT = Development and for non-dev wanted to write logs to Azure Blob Storage.

Question 1. How to use app builder before it's created for code if (app.Environment.IsDevelopment()) ? or I have to use Environment.GetEnvironmentVariable?

Question 2. can this be achieved without if/else block and within single line I can change the write context?

 public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddControllers();

        if (app.Environment.IsDevelopment())
        {
            builder.Host.UseSerilog((ctx, lc) => lc
                .WriteTo.Console());
        }
        else
        {
            builder.Host.UseSerilog((ctx, lc) => lc
            .WriteTo.AzureBlobStorage());
        }
user584018
  • 10,186
  • 15
  • 74
  • 160
  • 1
    Q1: `builder.Environment`. Q2: Probably, but that's more of an code-style issue, e.g. not really 'on-topic' here. I would not worry about it, it is more readable the way you already wrote it. – nilsK Oct 17 '22 at 15:23
  • 1
    You could add a `public static class ServiceContainerExtensions` and a `public static IServiceCollection SetupServiceCollection(this IServiceCollection services)` inside it. Call it from your Program.cs with `builder.Services.SetupServiceCollection();` if you want it cleaner. – nilsK Oct 17 '22 at 15:25
  • Could you please complete code snippet for `SetupServiceCollection`? – user584018 Oct 17 '22 at 15:45
  • Maybe better use the [configuration file](https://github.com/serilog/serilog-settings-configuration#serilogsettingsconfiguration--)? – Guru Stron Oct 17 '22 at 18:14
  • 1
    @user584018 [small fiddle here](https://dotnetfiddle.net/2HJ5xv) – nilsK Oct 19 '22 at 10:16

1 Answers1

1

As answered here you can access the environment from the builder itself:

if (builder.Environment.IsDevelopment())
{
   // ...
}

As for "clever" one-liners not much can be done here, I recommend to stick to the if-else as more readable approach (and potentially moving the Serilog setup logic to extension method), but just for funsies - abusing ternary with the discard:

_ = builder.Environment.IsDevelopment()
    ? builder.Host.UseSerilog((ctx, lc) => lc.WriteTo.Console())
    : builder.Host.UseSerilog((ctx, lc) => lc.WriteTo.AzureBlobStorage());

Or

builder.Host.UseSerilog((ctx, lc) => _ = builder.Environment.IsDevelopment()
        ? lc.WriteTo.Console()
        : lc.WriteTo.AzureBlobStorage()); 

But I hugely recommend considering the ability to set up the logger via configuration.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132