(精華)2020年7月20日 ASP.NET Core serilog日誌框架的使用

愚公搬程式碼發表於2020-07-20

首先安裝如下兩個包

Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.Elasticsearch

封裝使用

/// <summary>
/// 配置日誌
/// </summary>
/// <param name="hostBuilder">建造者</param>
/// <returns></returns>
public static IHostBuilder UseLog(this IHostBuilder hostBuilder)
{
    var rootPath = AppDomain.CurrentDomain.BaseDirectory;
    var path = Path.Combine(rootPath, "logs", "log.txt");

    return hostBuilder.UseSerilog((hostingContext, serilogConfig) =>
    {
        var envConfig = hostingContext.Configuration;

        LogConfig logConfig = new LogConfig();
        envConfig.GetSection("log").Bind(logConfig);

        logConfig.overrides.ForEach(aOverride =>
        {
            serilogConfig.MinimumLevel.Override(aOverride.source, aOverride.minlevel.ToEnum<LogEventLevel>());
        });

        serilogConfig.MinimumLevel.Is(logConfig.minlevel.ToEnum<LogEventLevel>());
        if (logConfig.console.enabled)
            serilogConfig.WriteTo.Console();
        if (logConfig.debug.enabled)
            serilogConfig.WriteTo.Debug();
        if (logConfig.file.enabled)
        {
            string template = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3} {SourceContext:l}] {Message:lj}{NewLine}{Exception}";

            serilogConfig.WriteTo.File(
                path,
                outputTemplate: template,
                rollingInterval: RollingInterval.Day,
                shared: true,
                fileSizeLimitBytes: 10 * 1024 * 1024,
                rollOnFileSizeLimit: true
                );
        }
        if (logConfig.elasticsearch.enabled)
        {
            var uris = logConfig.elasticsearch.nodes.Select(x => new Uri(x)).ToList();

            serilogConfig.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(uris)
            {
                IndexFormat = logConfig.elasticsearch.indexformat,
                AutoRegisterTemplate = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7
            });
        }
    });
}
public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseIdHelper()//分散式自增Id元件
            .UseLog()//使用serilog日誌框架
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CORE.WEBERP.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogInformation("開始");
            int a = 0;
            int b = 2;
            try
            {
                _logger.LogDebug("計算兩者相除");
                Console.WriteLine(b / a);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "計算出現意外的錯誤");
            }
            _logger.LogInformation("結束");
            var rng = new Random();

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

在這裡插入圖片描述
在這裡插入圖片描述

備註:其他函式請移到類庫中去檢視,本人部落格裡都有。

相關文章