I’ve looked at multiple StackOverflow answers and still cannot get Serilog to write to a sink beside the local console. Using --verbose
doesn’t reveal anything.
I’ve tried using as sinks:
- Console
- BetterStack
- GrafanaLoki
Again, the only one that works is Console.
I’m using .NET 8 and Azure Functions in Isolated Mode.
Here is my source:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using Serilog.Formatting.Compact;
using Serilog.Sinks.Grafana.Loki;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.BetterStack(sourceToken: "redacted")
.WriteTo.GrafanaLoki(
"https://logs-prod-us-central2.grafana.net",
credentials: new LokiCredentials()
{
Login = "######",
Password = "redacted"
})
.CreateLogger();
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
// I've tried uncommenting each of the three following lines, but nothing works.
//services.AddSerilog(Log.Logger, dispose: true);
//services.AddLogging(lb => lb.AddSerilog(dispose: true));
//services.AddSingleton<ILoggerProvider>(new SerilogLoggerProvider(logger));
})
.UseSerilog((ctx, cfg) =>
{
cfg.Enrich.WithProperty("Application", ctx.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", ctx.HostingEnvironment.EnvironmentName)
.WriteTo.Console(new RenderedCompactJsonFormatter());
})
.Build();
try
{
Log.Information("Starting the Host");
host.Run();
}
catch (Exception exc)
{
Log.Fatal(exc, "Host Terminated Unexpectedly");
}
Log.CloseAndFlush();