dotnet Core 学习(四):Logging
.net Core开发过程中日志记录非常的方便,只需要以下简单的几步操作就可以完成日志的输出:
1.引用类库
"Microsoft.Extensions.Logging": "1.1.0", "Microsoft.Extensions.Logging.Console": "1.1.0", "Microsoft.Extensions.Logging.Debug": "1.1.0"
2.简单的日志输出
Console窗口输出:
public static void Main(string[] args) { ILoggerFactory logFactory=new LoggerFactory(); //实例化日志工厂 logFactory.AddConsole(); //添加日志输出至Console窗口
logFactory.AddDebug(); //添加Debug输出
ILogger logger=logFactory.CreateLogger<Program>(); logger.LogInformation("TestLog"); Console.WriteLine("Hello World!"); }
输出内容如下:
3.日志文件
目前常用的日志工具Log4和NLog,好像只有Nlog首先支持了.NetCore。
在项目中引用NLog类库:
"NLog.Extensions.Logging": "1.0.0-rtm-alpha4"
并新增NLog的配置文件nlog.config
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
在代码中新增Nlog:
public static void Main(string[] args) { ILoggerFactory logFactory=new LoggerFactory(); //实例化日志工厂 logFactory.AddConsole(); //添加日志输出至Console窗口 logFactory.AddDebug(); //添加Debug输出 logFactory.AddNLog(); ILogger logger=logFactory.CreateLogger<Program>(); logger.LogInformation("TestLog"); Console.WriteLine("Hello World!"); }