Skip to content

Instantly share code, notes, and snippets.

@cognitive-arch
Created December 22, 2019 18:34
Show Gist options
  • Save cognitive-arch/e582fac189fc2fd8d26d4baf121c3e26 to your computer and use it in GitHub Desktop.
Save cognitive-arch/e582fac189fc2fd8d26d4baf121c3e26 to your computer and use it in GitHub Desktop.
Serilog.Sinks.RabbitMQ configuration in asp.net core API regards Issue 91
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Formatting.Json;
using Serilog.Sinks.RabbitMQ;
namespace SinkTestWeb
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Logger logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) =>
{
clientConfiguration.Port = 5672;
clientConfiguration.DeliveryMode = RabbitMQDeliveryMode.Durable;
clientConfiguration.Exchange = "test_exchange";
clientConfiguration.Username = "guest";
clientConfiguration.Password = "guest";
clientConfiguration.ExchangeType = "fanout";
clientConfiguration.Hostnames.Add("localhost");
sinkConfiguration.TextFormatter = new JsonFormatter();
}).CreateLogger();
var loggerFactory = new LoggerFactory();
#pragma warning disable CS0618 // Type or member is obsolete
loggerFactory
.AddSerilog()
.AddConsole(LogLevel.Information);
#pragma warning restore CS0618 // Type or member is obsolete
services.AddSingleton<ILoggerFactory>(loggerFactory);
}
// I tried to use the LoggerFactory in this configure method and as you recommended in services configuration
// but non of the way is working
public void Configure(IApplicationBuilder app, IHostingEnvironment env /* ,ILoggerFactory loggerFactory */)
{
// loggerFactory.AddSerilog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
namespace SinkTestWeb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private ILogger<ValuesController> _logger;
public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
_logger.LogError("This is demo Error at {0}", DateTime.UtcNow);
return new string[] { "value1", "value2" };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment