从 NuGet 安装 Serilog

核心的包是 SerilogSerilog.AspNetCore
建议安装 Serilog.AspNetCore,几乎包含了Serilog常用的所有包
异步写入 Serilog.Sinks.Async
写入MSSQL  Serilog.Sinks.MSSqlServer  

Install-Package Serilog.AspNetCore
Install-Package Serilog
Install-Package Serilog.Sinks.Async
Install-Package Serilog.Sinks.MSSqlServer

 

日志输出

输出到控制台

 1 using Serilog;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.ComponentModel;
 5 using System.IO;
 6 using System.Linq;
 7 
 8 namespace NetCoreConsoleApp
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Log.Logger = new LoggerConfiguration()
15             .WriteTo.Console()  //输出到控制台
16             .CreateLogger();
17 
18             Log.Information("log");
19 
20         }
21  
22 
23     }
24 }

 

 

输出到本地日志文件

WriteTo.File详解(日志默认路径为当前程序路径)

     path:默认路径是程序的bin目录+path参数,当然也可以写绝对路径,只需要写入参数就可以了
     rollingInterval:创建文件的类别,可以是分钟,小时,天,月。 此参数可以让创建的log文件名默认 + 时间。例如:log20191219.log
     outputTemplate:日志模板,可以自定义
     retainedFileCountLimit:设置日志文件个数最大值,默认31,意思就是只保留最近的31个日志文件,等于null时永远保留文件

 

 1 using Serilog;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.ComponentModel;
 5 using System.IO;
 6 using System.Linq;
 7 
 8 namespace NetCoreConsoleApp
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             /*
15             WriteTo.File详解 
16                 path:默认路径是程序的bin目录+path参数,当然也可以写绝对路径,只需要写入参数就可以了
17                 rollingInterval:创建文件的类别,可以是分钟,小时,天,月。 此参数可以让创建的log文件名 + 时间。例如log20191219.log
18                 outputTemplate:日志模板,可以自定义
19                 retainedFileCountLimit:设置日志文件个数最大值,默认31,意思就是只保留最近的31个日志文件,等于null时永远保留文件
20              */
21 
22 
23             string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 100);
24 
25             Log.Logger = new LoggerConfiguration()
26               .MinimumLevel.Debug() // 所有Sink的最小记录级别
27               .WriteTo.Console()    //输出到控制台
28               .WriteTo.File("00_Logs\\log.log", //$"{AppContext.BaseDirectory}00_Logs\log.log"
29                             rollingInterval: RollingInterval.Day,
30                             outputTemplate: SerilogOutputTemplate
31                             //,retainedFileCountLimit: 31
32                             )
33               .CreateLogger();
34             Log.Information("log");
35         }
36     }
37 }

 

输出到本地日志文件(异步)

需要Serilog.Sinks.Async包,github详解路径:https://github.com/serilog/serilog-sinks-async

 

 1 using Serilog;
 2 
 3 namespace NetCoreConsoleApp
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             //github详解路径:https://github.com/serilog/serilog-sinks-async
10 
11             Log.Logger = new LoggerConfiguration()
12           .WriteTo.Async(a => a.File("00_Logs\\log.log", rollingInterval: RollingInterval.Day))
13           .CreateLogger();
14             Log.Information("log");
15             Log.CloseAndFlush();
16         }
17     }
18 }

 

不同的日志级别输出到不同的文件夹下

 

using Serilog;
using Serilog.Events;
using System;

namespace NetCoreConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}00_Logs\{LogEvent}\log.log";
            string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 50);

            Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.MinimumLevel.Debug() // 所有Sink的最小记录级别
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.File(LogFilePath("Information"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File(LogFilePath("Error"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.CreateLogger();

            Log.Information("log");
            Log.Error("log");
        }
    }
}

 

输出到MSSQL 

需要Serilog.Sinks.MSSqlServergithub详解路径:https://github.com/serilog/serilog-sinks-mssqlserver

参考链接:https://www.cnblogs.com/lonelyxmas/p/11980881.html

using Serilog;
using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
using System;
using System.Collections.ObjectModel;
using System.Data;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {


            string connectionString = @"Server=....";string tableNameA = "LogsA";
            string tableNameB = "LogsB";
            string tableNameC = "LogsC";
            static void Write()
            {
                Log.Information("测试信息");
                Log.Error("Error");
                Log.Write(LogEventLevel.Error, new Exception("错误"), "致命错误");
            };


            //A:默认配置
            //autoCreateSqlTable为true 时 会自动创建日志表
            Log.Logger = new LoggerConfiguration().WriteTo.MSSqlServer(connectionString, tableNameA, autoCreateSqlTable: true).CreateLogger();
            Write();


            //B:移除列
            var options = new ColumnOptions();
            options.Store.Remove(StandardColumn.Properties);
            options.Store.Remove(StandardColumn.MessageTemplate);
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer(connectionString, tableNameB, columnOptions: options, autoCreateSqlTable: true)
                         .CreateLogger();
            Write();


            //C:添加自定义列
            options = new ColumnOptions();
            options.AdditionalColumns = new Collection<SqlColumn>
                {
                    new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },
                    new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP2" }
                };
            Log.Logger = new LoggerConfiguration()
                             .Enrich.WithProperty("IP", "8.8.8.8")
                             .Enrich.WithProperty("IP2", "9.9.9.9")
                             .WriteTo.MSSqlServer(connectionString, tableNameC, columnOptions: options, autoCreateSqlTable: true)
                             .CreateLogger();
            Write();



            Console.WriteLine("Hello World!");
            Console.ReadKey();

        }
    }
}

 

 

 ASP.NET Core 中使用 Serilog

参考链接:https://www.cnblogs.com/MaleDeer/p/10797509.html

在Program.cs程序启动时注入Serilog 加载配置

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {

            Log.Logger = new LoggerConfiguration()
             .MinimumLevel.Debug()
             .WriteTo.Console()
             .WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day)
             .CreateLogger();

            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            .UseSerilog();
    }
}

或者

using System;using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;

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

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseSerilog((hostingContext, loggerConfiguration) =>
                    {
                        loggerConfiguration
                       .ReadFrom.Configuration(hostingContext.Configuration)
                       .Enrich.FromLogContext()
                       .WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day)
                       .WriteTo.Console();
                    });
                });
    }
}

 

 

使用 Serilog 时,直接使用 ILogger 即可,因为此服务项目应该是默认注入了,此处需要依赖关系注入知识。如你不了解依赖关系注入,请看 微软官方文档

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly ILogger<ValuesController> _logger;

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

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            _logger.LogInformation("test info");
            return new string[] { "value1", "value2" };
        }
    }
}

 

 

相关链接 

 
 
 

版权声明:本文为RainFate原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/RainFate/p/12066138.html