集成Serilog失败
EminemJK opened this issue · 1 comments
EminemJK commented
/// <summary>
/// AOP 服务日志
/// </summary>
public class LogInterceptorAttribute : AbstractInterceptorAttribute
{
protected readonly ILogger Logger;
public string Title { get; set; }
private bool hasReturn { get; set; }
public LogInterceptorAttribute(string title, bool hasReturn = true)
{
this.Title = title;
this.Logger = Log.Logger;
this.hasReturn = hasReturn;
}
public async override Task Invoke(AspectContext context, AspectDelegate next)
{
try
{
await next(context);
Logger.Information($"service method {Title} responded succeed in {stopwatch.Elapsed.TotalMilliseconds.ToString("0.0000")} ms");
}
catch (Exception ex)
{
stopwatch.Stop();
Logger.Error(ex, $"service method {Title} responded failed")} ms");
if (hasReturn)
{
context.ReturnValue = null;
}
}
finally
{
Log.CloseAndFlush();
}
}
}
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.CreateBootstrapLogger();
try
{
Log.Information("Starting up!");
CreateHostBuilder(args).Build().Run();
Log.Information("Stopped cleanly");
}
catch (Exception ex)
{
Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().ConfigureAppConfiguration((hostContext,config)=>
{
}); ;
}).UseServiceProviderFactory(new ServiceContextProviderFactory());
}
protected readonly ILogger _logger;
protected readonly iuserService user;
public TestController(ILogger<TestController> logger, iuserService user)
{
_logger=logger;
this.user =user;
}
#region
[HttpGet]
public async Task<IActionResult> Login()
{
_logger.LogInformation("记录前面...");
await user.doSomethings();
_logger.LogInformation("记录后面..."); // this line no log
return View();
}
[LogInterceptor("测试")]
public async Task doSomethings() {}
“记录后面 ” 无法写入日志,删除“.UseServiceProviderFactory(new ServiceContextProviderFactory())”或删除“ [LogInterceptor("测试")]”,则可以正常输出日志。
日志情况:
2021-08-26 11:37:55.178 [INF] Now listening on: http://localhost:7000
2021-08-26 11:37:55.180 [INF] Application started. Press Ctrl+C to shut down.
2021-08-26 11:37:55.180 [INF] Hosting environment: Development
2021-08-26 11:37:55.181 [INF] Content root path: D:\Project\XXX
2021-08-26 11:37:57.475 [INF] HTTP GET / responded 200 in 917.3729 ms
2021-08-26 11:37:58.856 [INF] 记录前面
2021-08-26 11:37:58.994 [INF] service method 测试 responded succeed
EminemJK commented
将 this.Logger = Log.Logger; 删除,使用
var logger = context.ServiceProvider.GetService(typeof(ILogger)) as ILogger;
就成功了,有点莫名