.Core中使用Serilog

一、在控制台项目中使用

前提:引入Serilog.AspNetCore包

 新建一个Serilog帮助类SerilogHelper,定义两种方法,一个是将日志输出到console,一个是将日志输出到文件

using Serilog;
using System;
using System.IO;

namespace SerilogTest
{
    public static class SerilogHelper
    {
        /// 
        /// 输出到Console
        /// 
        public static void WriteToConsole()
        {
            //日志的输出模板
            string Logformat = @"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3} {SourceContext:l}] {Message:lj}{NewLine}{Exception}";
            //类似创建一个管道
            Log.Logger = new LoggerConfiguration()
                //设置最低等级
                .MinimumLevel.Debug()
                //将事件发送到控制台并展示
                .WriteTo.Console(outputTemplate: Logformat)
                .CreateLogger();

            //这里因为设置了最低等级为Debug,所以比Debug低的Verbose不会展示在控制台
            Log.Verbose("Verbose级别的日志消息");
            Log.Information("计算开始");

            try
            {
                int a = 0;
                int b = 5;
                Log.Debug("计算两者相除");
                Console.WriteLine(b / a);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "计算出现意外的错误");
            }
            Log.Information("计算结束");
        }

        public static void WriteToFile()
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", "log.txt");
            //日志的输出模板
            string Logformat = @"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3} {SourceContext:l}] {Message:lj}{NewLine}{Exception}";
            Log.Logger = new LoggerConfiguration()
              .MinimumLevel.Debug()
              //该行代码表示输出到console
              .WriteTo.Console(outputTemplate: Logformat)
              //第一个参数是文件路径,第二个参数是输出模板的选择,第三个参数是表示程序隔多长时间新创造一个日志文件
              .WriteTo.File(path, outputTemplate: Logformat, rollingInterval: RollingInterval.Day)
              .CreateLogger();

            //这里因为设置了最低等级为Debug,所以比Debug低的Verbose不会展示在控制台
            Log.Verbose("Verbose级别的日志消息");
            Log.Information("计算开始");

            try
            {
                int a = 0;
                int b = 5;
                Log.Debug("计算两者相除");
                Console.WriteLine(b / a);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "计算出现意外的错误");
            }
            Log.Information("计算结束");
        }
    }
}
View Code

在Program调用方法

namespace SerilogTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //SerilogHelper.WriteToConsole();
            SerilogHelper.WriteToFile();
        }        
    }
}

二、在web中使用Serilog

前提:引入Serilog.AspNetCore包

配置appsettings.json

{
  "log": { //日志配置
    "minlevel": "Verbose", //定义详见Serilog.Events.LogEventLevel
    "console": {
      "enabled": true
    },
    "debug": {
      "enabled": true
    },
    "file": {
      "enabled": true
    },
    "elasticsearch": {
      "enabled": false,
      "nodes": [ "http://localhost:9200/" ],
      "indexformat": "colder"
    },
    "overrides": [ //重写日志输出级别
      {
        "source": "Microsoft.AspNetCore",
        "minlevel": "Warning"
      },
      {
        "source": "Microsoft.EntityFrameworkCore",
        "minlevel": "Information"
      },
      {
        "source": "Microsoft.EntityFrameworkCore.Infrastructure",
        "minlevel": "Warning"
      }
    ]
  },
  "AllowedHosts": "*"
}
View Code

新建一个对应appsettings.json的model

using System.Collections.Generic;

namespace SerilogWebTest
{
    public class LogConfig
    {
        public string minlevel { get; set; }
        public Option console { get; set; } = new Option();
        public Option debug { get; set; } = new Option();
        public Option file { get; set; } = new Option();
        public Option elasticsearch { get; set; } = new Option();
        public List overrides { get; set; } = new List();
    }

    public class Option
    {
        public bool enabled { get; set; }
        public List<string> nodes { get; set; } = new List<string>();
        public string indexformat { get; set; }
    }

    public class OverrideConfig
    {
        public string source { get; set; }
        public string minlevel { get; set; }
    }
}

定义IHostBuilder扩展类,配置Serilog

using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using System.Linq;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace SerilogWebTest
{
    public static partial class Extention
    {
        /// 
        /// 将枚举类型的文本转为枚举类型
        /// 
        /// 枚举类型
        /// 枚举文本
        /// 
        public static TEnum ToEnum(this string enumText) where TEnum : struct
        {
            Enum.TryParse(enumText, out TEnum value);
            return value;
        }
        public static IHostBuilder UseLog(this IHostBuilder hostBuilder)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "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());
                });

                serilogConfig.MinimumLevel.Is(logConfig.minlevel.ToEnum());
                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
                    });
                }
            });
        }
    }

    
}
View Code

扩展类中除了允许将日志输出到console、文件,还允许输出到elasticsearch

如果要输出到elasticsearch,需要引入包

 在Program中注入日志服务

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace SerilogWebTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseLog()//注入服务
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                });       
        
    }
    
}

三、elasticsearch

在前边的web项目中,我们提供了输出到elasticsearch的方法。什么是elasticsearch,其实就是一个nosql,是一个开源的分布式 RESTful 搜索和分析引擎,基于Lucene的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。ElasticSearch用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便Elasticsearch是一个Java应用程序,需要安装JAVA环境。。官方客户端在Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby和许多其他语言中都是可用的。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr,也是基于Lucene。

这里对elasticsearch不做详细的介绍,我这里眼下不使用elasticsearch,如果感兴趣可以看下官网文档https://www.elastic.co/cn/

四、以上demo源码见https://github.com/qiuxianhu/CoreComponentDemo

你可能感兴趣的:(.Core中使用Serilog)