集成 Serilog

本文示例源码:https://github.com/liangshiw/LogDashboard/tree/master/samples/UseSerilog

前言

serilog是NET下优秀的日志项目,对NETCore支持友好,扩展丰富。abp框架更是将其做为框架默认的日志组件,logdashboard完全支持serilog

创建NETCore项目

如同快速入门一样,我们需要创建一个NETCore项目,不在赘述此过程

安装 Serilog

Install-Package Serilog.AspNetCore

使用以下代码覆盖 Program

public static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.File($"{AppContext.BaseDirectory}Log/.log", rollingInterval:RollingInterval.Day,outputTemplate: "{Timestamp:HH:mm} || {Level} || {SourceContext:l} || {Message} || {Exception} ||end {NewLine}")
        .CreateLogger();

    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseSerilog()
        .UseStartup<Startup>();

安装LogDashboard

Install-Package LogDashboard

打开Startup.cs

ConfigureServices方法中配置服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogDashboard();
}

Configure方法中配置中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseLogDashboard();

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

运行项目导航到/logdashboard

enjoy

Last updated