前几天把基于quartz.net的部分项目代码移植到了dotnet core ,但是没增加日志功能,原因是没找到合适的组件。
今天终于找到了Serilog: https://github.com/serilog/serilog
就大概讲一下:
1, vs 2015 新建Console Application (.NET Core) 项目。
2, 程序包管理器控制台:
安装如下组件:Serilog,Serilog.Sinks.Literate,Serilog.Sinks.RollingFile
或者project.json 配置:
"Serilog": "2.2.0",
"Serilog.Sinks.Literate": "2.0.0",
"Serilog.Sinks.RollingFile": "3.0.0"
3,写点代码:
using Serilog; using System; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug()//等级 .WriteTo.LiterateConsole()//写到控制台 .WriteTo.RollingFile("logs\{Date}.txt")//写到文本 .CreateLogger(); Log.Information("Hello, world!"); int a = 10, b = 0; try { Log.Debug("Dividing {A} by {B}", a, b); Console.WriteLine(a / b); } catch (Exception ex) { Log.Error(ex, "Something went wrong"); } Log.CloseAndFlush(); Console.ReadKey(); } } }
4,运行下看看: