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

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

 

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

 

 

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

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

 

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

 

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

 

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

 

 

  1. using Serilog;
  2. using Serilog.Events;
  3. using System;
  4. namespace NetCoreConsoleApp
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}00_Logs\{LogEvent}\log.log";
  11. string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 50);
  12. Log.Logger = new LoggerConfiguration()
  13. .Enrich.FromLogContext()
  14. .WriteTo.Console()
  15. .MinimumLevel.Debug() // 所有Sink的最小记录级别
  16. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  17. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.File(LogFilePath("Information"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  18. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  19. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File(LogFilePath("Error"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  20. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
  21. .CreateLogger();
  22. Log.Information("log");
  23. Log.Error("log");
  24. }
  25. }
  26. }

 

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

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

  1. using Serilog;
  2. using Serilog.Events;
  3. using Serilog.Sinks.MSSqlServer;
  4. using System;
  5. using System.Collections.ObjectModel;
  6. using System.Data;
  7. namespace ConsoleApp1
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. string connectionString = @"Server=....";string tableNameA = "LogsA";
  14. string tableNameB = "LogsB";
  15. string tableNameC = "LogsC";
  16. static void Write()
  17. {
  18. Log.Information("测试信息");
  19. Log.Error("Error");
  20. Log.Write(LogEventLevel.Error, new Exception("错误"), "致命错误");
  21. };
  22. //A:默认配置
  23. //autoCreateSqlTable为true 时 会自动创建日志表
  24. Log.Logger = new LoggerConfiguration().WriteTo.MSSqlServer(connectionString, tableNameA, autoCreateSqlTable: true).CreateLogger();
  25. Write();
  26. //B:移除列
  27. var options = new ColumnOptions();
  28. options.Store.Remove(StandardColumn.Properties);
  29. options.Store.Remove(StandardColumn.MessageTemplate);
  30. Log.Logger = new LoggerConfiguration()
  31. .WriteTo.MSSqlServer(connectionString, tableNameB, columnOptions: options, autoCreateSqlTable: true)
  32. .CreateLogger();
  33. Write();
  34. //C:添加自定义列
  35. options = new ColumnOptions();
  36. options.AdditionalColumns = new Collection<SqlColumn>
  37. {
  38. new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },
  39. new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP2" }
  40. };
  41. Log.Logger = new LoggerConfiguration()
  42. .Enrich.WithProperty("IP", "8.8.8.8")
  43. .Enrich.WithProperty("IP2", "9.9.9.9")
  44. .WriteTo.MSSqlServer(connectionString, tableNameC, columnOptions: options, autoCreateSqlTable: true)
  45. .CreateLogger();
  46. Write();
  47. Console.WriteLine("Hello World!");
  48. Console.ReadKey();
  49. }
  50. }
  51. }

 

 

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

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

  1. using System;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.Extensions.Hosting;
  4. using Serilog;
  5. namespace WebApplication1
  6. {
  7. public class Program
  8. {
  9. public static void Main(string[] args)
  10. {
  11. Log.Logger = new LoggerConfiguration()
  12. .MinimumLevel.Debug()
  13. .WriteTo.Console()
  14. .WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day)
  15. .CreateLogger();
  16. try
  17. {
  18. Log.Information("Starting up");
  19. CreateHostBuilder(args).Build().Run();
  20. }
  21. catch (Exception ex)
  22. {
  23. Log.Fatal(ex, "Application start-up failed");
  24. }
  25. finally
  26. {
  27. Log.CloseAndFlush();
  28. }
  29. }
  30. public static IHostBuilder CreateHostBuilder(string[] args) =>
  31. Host.CreateDefaultBuilder(args)
  32. .ConfigureWebHostDefaults(webBuilder =>
  33. {
  34. webBuilder.UseStartup<Startup>();
  35. })
  36. .UseSerilog();
  37. }
  38. }

或者

  1. using System;using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.Extensions.Hosting;
  3. using Serilog;
  4. namespace WebApplication1
  5. {
  6. public class Program
  7. {
  8. public static void Main(string[] args)
  9. {
  10. CreateHostBuilder(args).Build().Run();
  11. }
  12. public static IHostBuilder CreateHostBuilder(string[] args) =>
  13. Host.CreateDefaultBuilder(args)
  14. .ConfigureWebHostDefaults(webBuilder =>
  15. {
  16. webBuilder.UseStartup<Startup>();
  17. webBuilder.UseSerilog((hostingContext, loggerConfiguration) =>
  18. {
  19. loggerConfiguration
  20. .ReadFrom.Configuration(hostingContext.Configuration)
  21. .Enrich.FromLogContext()
  22. .WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day)
  23. .WriteTo.Console();
  24. });
  25. });
  26. }
  27. }

 

 

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

  1. using System.Collections.Generic;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Logging;
  4. namespace WebApplication1.Controllers
  5. {
  6. [Route("api/[controller]")]
  7. [ApiController]
  8. public class ValuesController : ControllerBase
  9. {
  10. private readonly ILogger<ValuesController> _logger;
  11. public ValuesController(ILogger<ValuesController> logger)
  12. {
  13. _logger = logger;
  14. }
  15. // GET api/values
  16. [HttpGet]
  17. public ActionResult<IEnumerable<string>> Get()
  18. {
  19. _logger.LogInformation("test info");
  20. return new string[] { "value1", "value2" };
  21. }
  22. }
  23. }

 

 

 
 
 

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