服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - .Net Core项目如何添加日志功能详解

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

2020-05-29 15:35MicroHeart! ASP.NET教程

这篇文章主要给大家介绍了关于.Net Core项目如何添加日志功能的相关资料,日志功能是我们开发中经常需要用到的一个功能,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧

一、微软内置的日志组件

在.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配置不同。如下:

?
1
2
3
4
5
6
7
8
9
10
{
 "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项目如何添加日志功能详解

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();
 }
 }

配置文件为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
 "AppSettings": {
 "Url": "http://0.0.0.0:6000"
 },
 "Logging": {
 "IncludeScopes": false,
 "Debug": {
 "LogLevel": {
 "Default": "Info"
 }
 },
 "Console": {
 "LogLevel": {
 "Default": "Warning"
 }
 }
 }
}

StartUp为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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中添加以下代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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}" />//将日志通过网络输出
 <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,就可以使用了。

总结

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

原文链接:https://www.cnblogs.com/MicroHeart/p/9268596.html

延伸 · 阅读

精彩推荐