|
| 1 | +using System; |
| 2 | +using System.Threading.Tasks; |
| 3 | +using Microsoft.Extensions.DependencyInjection; |
| 4 | +using Microsoft.Extensions.Hosting; |
| 5 | +using Serilog; |
| 6 | +using Serilog.Core; |
| 7 | +using Serilog.Filters; |
| 8 | + |
| 9 | +namespace SerilogLog; |
| 10 | + |
| 11 | +class Program |
| 12 | +{ |
| 13 | + static async Task Main(string[] args) |
| 14 | + { |
| 15 | + Log.Logger = new LoggerConfiguration() |
| 16 | + .Enrich.FromLogContext() |
| 17 | + .MinimumLevel.Debug() |
| 18 | + .WriteTo.Console() |
| 19 | + .WriteTo.Logger(l => l |
| 20 | + .Filter |
| 21 | + .ByIncludingOnly(Matching.FromSource("QuickFix.SessionLogs")) |
| 22 | + .Filter |
| 23 | + .ByIncludingOnly("EventId.Id in [7702, 7703]") // QuickFix.Logger.LogEventIds.IncomingMessage.Id |
| 24 | + // and .OutgoingMessage.Id |
| 25 | + .WriteTo.Map(Constants.SourceContextPropertyName, "", (source, lc) => |
| 26 | + { |
| 27 | + var fileName = GetSessionIdFromSourceContext(source); |
| 28 | + lc.File($"log/{fileName}.messages.log", rollingInterval: RollingInterval.Hour, outputTemplate:"{Message:lj}{NewLine}"); |
| 29 | + }) |
| 30 | + ) |
| 31 | + .WriteTo.Logger(l => l |
| 32 | + .Filter |
| 33 | + .ByIncludingOnly(Matching.FromSource("QuickFix.SessionLogs")) |
| 34 | + .Filter |
| 35 | + .ByExcluding("EventId.Id in [7702, 7703]") |
| 36 | + .WriteTo.Map(Constants.SourceContextPropertyName, "", (source, lc) => |
| 37 | + { |
| 38 | + var fileName = GetSessionIdFromSourceContext(source); |
| 39 | + lc.File($"log/{fileName}.event.log", rollingInterval: RollingInterval.Hour, outputTemplate:"{Message:lj}{NewLine}"); |
| 40 | + }) |
| 41 | + ) |
| 42 | + .WriteTo.Logger(l => l |
| 43 | + .Filter |
| 44 | + .ByIncludingOnly(Matching.FromSource("QuickFix")) |
| 45 | + .Filter |
| 46 | + .ByExcluding(Matching.FromSource("QuickFix.SessionLogs")) |
| 47 | + .WriteTo.File("log/Non-Session-Log.event.current.log") |
| 48 | + ) |
| 49 | + .CreateLogger(); |
| 50 | + |
| 51 | + try |
| 52 | + { |
| 53 | + Log.Information("Starting host"); |
| 54 | + |
| 55 | + var builder = Host.CreateApplicationBuilder(args); |
| 56 | + builder.Services.AddHostedService<FixBackgroundService>(); |
| 57 | + builder.Services.AddSerilog(); |
| 58 | + builder.Services.Configure<AppSettings>(builder.Configuration); |
| 59 | + var app = builder.Build(); |
| 60 | + |
| 61 | + await app.RunAsync(); |
| 62 | + } |
| 63 | + catch (Exception ex) |
| 64 | + { |
| 65 | + Log.Fatal(ex, "Host terminated unexpectedly"); |
| 66 | + } |
| 67 | + finally |
| 68 | + { |
| 69 | + await Log.CloseAndFlushAsync(); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + private static string GetSessionIdFromSourceContext(string sourceContext) |
| 74 | + { |
| 75 | + // Log source is "QuickFix.SessionLogs.<session-id>", this returns <session-id> |
| 76 | + var i = sourceContext.IndexOf('.', sourceContext.IndexOf('.') + 1) + 1; |
| 77 | + return sourceContext[i..]; |
| 78 | + } |
| 79 | +} |
0 commit comments