第一步:安装Serilog
使用NuGet包安装以下组件:
Serilog.AspNetCore
Serilog.Settings.Configuration
Serilog.Sinks.Console
Serilog.Sinks.Elasticsearch
第二步:修改Program.cs文件
public class Program { public static readonly string Namespace = typeof(Program).Namespace; public static readonly string AppName = Namespace.Substring(Namespace.LastIndexOf('.', Namespace.LastIndexOf('.') - 1) + 1); public static int Main(string[] args) { var configuration = GetConfiguration(); Log.Logger = CreateSerilogLogger(configuration); try { Log.Information("Configuring web host ({ApplicationContext})...", AppName); var host = BuildWebHost(configuration, args); Log.Information("Starting web host ({ApplicationContext})...", AppName); host.Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Program terminated unexpectedly ({ApplicationContext})!", AppName); return 1; } finally { Log.CloseAndFlush(); } } private static ILogger CreateSerilogLogger(IConfiguration configuration) { // var seqServerUrl = configuration["Serilog:SeqServerUrl"]; return new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.WithProperty("ApplicationContext", AppName) .Enrich.FromLogContext() .WriteTo.Console(new ElasticsearchJsonFormatter()) // .WriteTo.Console() // .WriteTo.Seq(string.IsNullOrWhiteSpace(seqServerUrl) ? "http://seq" : seqServerUrl) //写入sql .ReadFrom.Configuration(configuration) .CreateLogger(); } private static IConfiguration GetConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); return builder.Build(); } private static IWebHost BuildWebHost(IConfiguration configuration, string[] args) => WebHost.CreateDefaultBuilder(args) .CaptureStartupErrors(false) .UseStartup<Startup>() .UseConfiguration(configuration) .UseSerilog() .Build(); }
第三步:修改appsettings.json文件
{ "Serilog": { "Using": [ "Serilog.Sinks.Console" ], "MinimumLevel": "Verbose", "WriteTo": [ { "Name": "Console" } ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "Destructure": [ { "Name": "ToMaximumDepth", "Args": { "maximumDestructuringDepth": 4 } }, { "Name": "ToMaximumStringLength", "Args": { "maximumStringLength": 100 } }, { "Name": "ToMaximumCollectionCount", "Args": { "maximumCollectionCount": 10 } } ], "Properties": { "Application": "deploy-demo" } }, "AllowedHosts": "*" }
第四步:打包成镜像运行
docker run -d -p 8003:80 --log-driver=fluentd --link elasticsearch --log-opt fluentd-address=192.168.0.186:24224 --network net_db --name deploydemo imagename