欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.Net Core項(xiàng)目如何添加日志功能詳解

 更新時(shí)間:2018年07月13日 16:04:38   作者:MicroHeart!  
這篇文章主要給大家介紹了關(guān)于.Net Core項(xiàng)目如何添加日志功能的相關(guān)資料,日志功能是我們開發(fā)中經(jīng)常需要用到的一個(gè)功能,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、微軟內(nèi)置的日志組件

在.Net Core中使用模板新建的Web Api項(xiàng)目時(shí),會自動(dòng)加入日志功能。只需要在控制器中注入ILogger就可以了。命名空間為:Microsoft.Extensions.Logging。

會發(fā)現(xiàn)只有Error被打印到了控制臺,Trace沒有被打印。那是因?yàn)樵赼ppsetting.json中配置了Logging>Console>Default的等級為Debug,日志的等級大于等于Debug才會輸出到控制臺。在這里說一下LogLevel:Trace<Debug<Information<Warning<Error<Critical<None。

當(dāng)打開appsettings.development.json文件你會發(fā)現(xiàn)跟appsettings.json配置不同。如下:

{
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
 "Default": "Debug",
 "System": "Information",
 "Microsoft": "Information"
 }
 }
}

例如:

"System": "Information" 表示命名空間以System開頭的類中且日志等級大于等于Information才會輸出到控制臺。

"Default": "Debug" 表示除以System和Microsoft開頭的命名空間日志等級大約等于Debug才會輸出到控制臺。

這里說明一下到底是在什么時(shí)候,讀取了appsettings.json中的配置了了? 其實(shí)是在Program中 WebHost.CreateDefaultBuilder(arge)

打開源碼發(fā)現(xiàn)

當(dāng)然我們可以不用微軟提供的默認(rèn)配置

public class Program
 {
 public static void Main(string[] args)
 {
  //指定配置文件路徑
  var configBuilder = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile($"appsettings.json", true, true)
    .AddJsonFile($"appsettings.{EnvironmentName.Development}.json", true, true);

  var config = configBuilder.Build();
  
  var host = new WebHostBuilder()
   .UseKestrel()
   .UseStartup<Startup>()
   .UseContentRoot(Directory.GetCurrentDirectory())
   .UseUrls(config["AppSettings:Url"])//設(shè)置啟動(dòng)時(shí)的地址
   .Build();
  host.Run();
 }
 }

配置文件為:

{
 "AppSettings": {
 "Url": "http://0.0.0.0:6000"
 },
 "Logging": {
 "IncludeScopes": false,
 "Debug": {
 "LogLevel": {
 "Default": "Info"
 }
 },
 "Console": {
 "LogLevel": {
 "Default": "Warning"
 }
 }
 }
}

StartUp為:

public class Startup
 {
 public IConfiguration Configuration { get; private set; }
 public Startup(IHostingEnvironment env)//在構(gòu)造函數(shù)中注入 IHostingEnvironment 
 {
  Configuration = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile($"appsettings.json")
    .Build();
 }
 public void ConfigureServices(IServiceCollection services)
 {
  services.AddMvc();
 }

 public void Configure(IApplicationBuilder app,
  IHostingEnvironment env,
  ILoggerFactory loggerFactory)
 {
  if (env.IsDevelopment())
  {
  app.UseDeveloperExceptionPage();
  }
  //添加控制臺輸出
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseMvc();
 }
 }

但是微軟提供的內(nèi)置的日志組件沒有實(shí)現(xiàn)將日志記錄到文件、數(shù)據(jù)庫上。下面介紹NLog

二、NLog

首先使用NuGet添加NLog,然后在Startup的Configure中添加以下代碼

public void Configure(IApplicationBuilder app,
  IHostingEnvironment env,
  ILoggerFactory loggerFactory)
 {
  if (env.IsDevelopment())
  {
  app.UseDeveloperExceptionPage();
  }
  //添加控制臺輸出
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  loggerFactory.AddNLog();//添加NLog
  NLog.LogManager.LoadConfiguration($@"{env.ContentRootPath}/nlog.config");//指定NLog的配置文件

  app.UseMvc();
 }

配置NLog的配置文件

<?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"
 autoReload="true">
 <!--internalLogLevel="Warn"
 internalLogFile="internal-nlog.txt">-->
 <targets>
 <target name="allfile" xsi:type="File" fileName="./logs/${shortdate}/all.log" layout="${longdate}|${message} ${exception}" />
 <target name="debugfile" xsi:type="File" fileName="./logs/${shortdate}/debug.log" layout="${longdate}|${message} ${exception}" />
 <target name="infofile" xsi:type="File" fileName="./logs/${shortdate}/info.log" layout="${longdate}|${message} ${exception}" />
 <target name="warnfile" xsi:type="File" fileName="./logs/${shortdate}/warn.log" layout="${longdate}|${message} ${exception}" />
 <target name="errorfile" xsi:type="File" fileName="./logs/${shortdate}/error.log" layout="${longdate}|${message} ${exception}" />
 <target name="fatalfile" xsi:type="File" fileName="./logs/${shortdate}/fatal.log" layout="${longdate}|${message} ${exception}" />
   <target name="network" xsi:type="Network" address="udp://chinacloudapp.cn:4561" layout="Development|${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />//將日志通過網(wǎng)絡(luò)輸出
 <target name="debuge" xsi:type="Console"/>//將日志輸出到控制臺
 </targets>

 <rules>
 <logger name="*" minlevel="Trace" writeTo="allfile,debuge" />
 <logger name="*" level="Info" writeTo="infofile" />
 <logger name="*" level="debug" writeTo="debugfile" />
 <logger name="*" level="warn" writeTo="warnfile" />
 <logger name="*" level="error" writeTo="errorfile" />
 <logger name="*" level="fatal" writeTo="fatalfile" />
 
 </rules>
</nlog>

xsi:type=“File”存儲日志為文件格式 ,

xsi:type="Console" 表示為控制臺輸出。

fileName="./logs/${shortdate}/all.log" 表示存儲文件路徑。

layout="${longdate}|${message} ${exception}" 表示為文件內(nèi)容的布局。

rules標(biāo)簽下面表示,對應(yīng)等級的日志寫到對應(yīng)target中。如

<logger name="*" level="Info" writeTo="infofile" /> 表示等級為Info的日志寫到target名稱為infofile的文件中。

<logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> 表示日志等級大于Trace的日志寫到target名稱為allfile和debuge(控制臺輸出)中。

同樣在使用的時(shí)候,只需要在用到的地方注入ILogger,就可以使用了。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論