using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Events; using Serilog.Sinks.Email; using System; using System.Net; namespace IRaCIS.Core.API { public class SerilogExtension { public static void AddSerilogSetup(string environment, IServiceProvider serviceProvider) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration( new ConfigurationBuilder() .AddJsonFile($"appsettings.{environment}.json") .Build()) //.Enrich.WithClientIp() //.Enrich.WithClientAgent() .Enrich.FromLogContext() .Enrich.WithHttpContextInfo(serviceProvider) .CreateLogger(); //Log.Information("Hello, world!"); //Log.Information("About to process input: ..."); //Log.Verbose("Verbose - Ah, there you are!"); //Log.Debug("Debug - Ah, there you are!"); //Log.Information("Information - Ah, there you are!"); //Log.Warning("Warning - Ah, there you are!"); //Log.Error("Error - Ah, there you are!"); //Log.Fatal("Fatal - ErrorAh, there you are!"); //var config = new LoggerConfiguration() // .MinimumLevel.Information() // .MinimumLevel.Override("Microsoft", LogEventLevel.Information) // // Filter out ASP.NET Core infrastructre logs that are Information and below 日志太多了 一个请求 记录好几条 // .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) // .MinimumLevel.Override("Hangfire", LogEventLevel.Warning) // .MinimumLevel.Override("System.Net.Http.HttpClient.HttpReports", LogEventLevel.Warning) // .Enrich.WithClientIp() // .Enrich.WithClientAgent() // .Enrich.FromLogContext() // //控制台 方便调试 问题 我们显示记录日志 时 获取上下文的ip 和用户名 用户类型 // .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Warning, // outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} ] {LocalIP} {ClientIp} {TokenUserRealName} {TokenUserType} {Message:lj} {Properties:j}{NewLine} {Exception}") // .WriteTo.File($"{AppContext.BaseDirectory}Serilogs/.log", rollingInterval: RollingInterval.Day, // outputTemplate: "{Timestamp:HH:mm:ss} || {Level} || {SourceContext:l} || {Message} ||{Exception} ||end {NewLine}"); ////扩展方法 获取上下文的ip 用户名 用户类型 //Log.Logger = config.Enrich.WithHttpContextInfo(serviceProvider).CreateLogger(); } } }