Skip to content

Instantly share code, notes, and snippets.

@crunchie84
Created December 3, 2015 14:20
Show Gist options
  • Save crunchie84/bcd6f7a8168b345a53ff to your computer and use it in GitHub Desktop.
Save crunchie84/bcd6f7a8168b345a53ff to your computer and use it in GitHub Desktop.
Serilog config for RX pushing to redis
public class MvcApplication : HttpApplication
{
private static void initializeLogging()
{
var loggerConfiguration = new LoggerConfiguration()
.Enrich.WithProperty("type", "application")
.Enrich.WithProperty("application", "my-app-name")
.Enrich.WithProperty("application_version", "1.2.3.4")
.Enrich.WithProperty("environment", "development")
.Enrich.With<Serilog.Extras.Web.Enrichers.HttpRequestIdEnricher>()
.MinimumLevel.Debug();
// https://github.com/serilog/serilog/blob/master/src/Serilog.Extras.Web/Extras/Web/ApplicationLifecycleModule.cs
// logs http start + end events
Serilog.Extras.Web.ApplicationLifecycleModule.IsEnabled = true;
var redisConnectionString = ConfigurationManager.ConnectionStrings["CentralizedLogging.RedisConnectionString"].ConnectionString;
try
{
var redisClient = ConnectionMultiplexer.Connect(redisConnectionString);
var db = redisClient.GetDatabase();
loggerConfiguration = configureCentralizedRedisLogging(loggerConfiguration, db);
}
catch (Exception)
{
// it is possible that we have reverted to tracelogging due to initialization issues
loggerConfiguration = loggerConfiguration.WriteTo.Trace();
}
Log.Logger = loggerConfiguration.CreateLogger();
}
private static LoggerConfiguration configureCentralizedRedisLogging(LoggerConfiguration loggerConfiguration, IDatabase db)
{
var jsonFormatter = new Serilog.Formatting.Json.JsonFormatter(false, null, true);
loggerConfiguration = loggerConfiguration
.WriteTo.Observers(logEvents => logEvents
.Buffer(TimeSpan.FromSeconds(10), 200) //output whatever we got after 10 seconds or after we have bundled 200 items
.Select(bufferedEvents => bufferedEvents.Select(evt =>
{
var sb = new StringBuilder();
var sw = new StringWriter(sb, CultureInfo.InvariantCulture);
jsonFormatter.Format(evt, sw);
return sb.ToString();
}))
.Where(serializedValues => serializedValues.Any())
.Subscribe(serializedValues =>
{
try
{
var redisValueArray = serializedValues.Select(str => (RedisValue)str).ToArray();
db.ListRightPush(@"logstash:redis", redisValueArray, CommandFlags.PreferMaster | CommandFlags.FireAndForget);
}
catch (Exception e)
{
Trace.TraceError("Could not submit log messages to redis cache, no logs will be written! " + e.Message);
}
},
exception => Trace.TraceError("Error while processing logs to redis" + exception.Message))
);
return loggerConfiguration;
}
protected void Application_Start()
{
initializeLogging();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment