无为清净楼资源网 Design By www.qnjia.com

一、微软内置的日志组件

在.Net Core中使用模板新建的Web Api项目时,会自动加入日志功能。只需要在控制器中注入ILogger就可以了。命名空间为:Microsoft.Extensions.Logging

.Net Core项目如何添加日志功能详解

会发现只有Error被打印到了控制台,Trace没有被打印。那是因为在appsetting.json中配置了Logging>Console>Default的等级为Debug,日志的等级大于等于Debug才会输出到控制台。在这里说一下LogLevel:Trace<Debug<Information<Warning<Error<Critical<None

当打开appsettings.development.json文件你会发现跟appsettings.json配置不同。如下:

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

例如:

"System": "Information" 表示命名空间以System开头的类中且日志等级大于等于Information才会输出到控制台。

"Default": "Debug" 表示除以System和Microsoft开头的命名空间日志等级大约等于Debug才会输出到控制台。

这里说明一下到底是在什么时候,读取了appsettings.json中的配置了了? 其实是在Program中 WebHost.CreateDefaultBuilder(arge)

打开源码发现

.Net Core项目如何添加日志功能详解

当然我们可以不用微软提供的默认配置

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"])//设置启动时的地址
   .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)//在构造函数中注入 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();
 }
 }

但是微软提供的内置的日志组件没有实现将日志记录到文件、数据库上。下面介绍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的配置文件

<"1.0" encoding="utf-8" "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}" />//将日志通过网络输出
 <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}" 表示为文件内容的布局。

rules标签下面表示,对应等级的日志写到对应target中。如

<logger name="*" level="Info" writeTo="infofile" /> 表示等级为Info的日志写到target名称为infofile的文件中。

<logger name="*" minlevel="Trace" writeTo="allfile,debuge" /> 表示日志等级大于Trace的日志写到target名称为allfile和debuge(控制台输出)中。

同样在使用的时候,只需要在用到的地方注入ILogger,就可以使用了。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

标签:
asp.net,core,日志,.net,core,日志,asp.net,core的日志

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。