一、微软内置的日志组件
在.Net Core中使用模板新建的Web Api项目时,会自动加入日志功能。只需要在控制器中注入ILogger就可以了。命名空间为:Microsoft.Extensions.Logging。
会发现只有Error被打印到了控制台,Trace没有被打印。那是因为在appsetting.json中配置了Logging>Console>Default的等级为Debug,日志的等级大于等于Debug才会输出到控制台。在这里说一下LogLevel:Trace 当打开appsettings.development.json文件你会发现跟appsettings.json配置不同。如下: 例如: "System": "Information" 表示命名空间以System开头的类中且日志等级大于等于Information才会输出到控制台。 "Default": "Debug" 表示除以System和Microsoft开头的命名空间日志等级大约等于Debug才会输出到控制台。 这里说明一下到底是在什么时候,读取了appsettings.json中的配置了了? 其实是在Program中 WebHost.CreateDefaultBuilder(arge) 。 打开源码发现 当然我们可以不用微软提供的默认配置 配置文件为: StartUp为: 但是微软提供的内置的日志组件没有实现将日志记录到文件、数据库上。下面介绍NLog 二、NLog 首先使用NuGet添加NLog,然后在Startup的Configure中添加以下代码 配置NLog的配置文件 xsi:type=“File”存储日志为文件格式 , xsi:type="Console" 表示为控制台输出。 fileName="./logs/${shortdate}/all.log" 表示存储文件路径。 layout="${longdate}|${message} ${exception}" 表示为文件内容的布局。 rules标签下面表示,对应等级的日志写到对应target中。如 同样在使用的时候,只需要在用到的地方注入ILogger,就可以使用了。 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对考高分网的支持。
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
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
{
"AppSettings": {
"Url": "http://0.0.0.0:6000"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Info"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
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();
}
}
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();
}



