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

首先安装如下两个包

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();
        }
    }
}

在这里插入图片描述
在这里插入图片描述

备注:其他函数请移到类库中去查看,本人博客里都有。

©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页