一、微软内置的日志组件

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

会发现只有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)。打开源码发现

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

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的配置文件

<?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,就可以使用了。

.Net Core项目添加日志功能的更多相关文章

  1. (译)Windsor入门教程---第五部分 添加日志功能

    介绍     现在我们已经有了基础的框架了,是时候添加内容了,那么我们首先应该考虑的就是在应用程序中添加日志功能.我们会使用Windsor来配置,在这一部分,你将学习Windsor之外的其他功能. L ...

  2. 如何使用vs将asp.net core项目添加容器支持并发布docker镜像到私有dockerhub和添加k8s/helm管理

    这篇文章介绍一下,如何使用VS2017给asp.net core添加容器支持,并发布镜像到私有docker hub,然后用chart管理容器镜像的操作流程. 话不多说,just do it. 新建项目 ...

  3. ASP.NET Boilerplate Castle容器无缝添加日志功能

    以添加log4net日志框架为例进行讲解 1.通常log4net的配置参数放在单独的配置文件中,但也可以写在web.config中,这里在我们的web项目中添加log4net.config应用配置文件 ...

  4. 如何通过注解方式给项目添加Swagger功能

    在Java后端,每次开发一个新的接口后需要自测,此时可以借助Swagger功能很好地完成自测,下面将通过注解的方式来添加Swagger. (1)代码部分 package com.bien.edge; ...

  5. springboot 切面添加日志功能

    1.新建一个springboot项目 2.定义个切面类,并指定切入点,获取所需记录信息(如:访问人IP, 访问地址,访问地址名称等) 3.新建数据库 SET FOREIGN_KEY_CHECKS=0; ...

  6. django中添加日志功能

    官方文档 猛戳这里 在settings中配置以下代码 #LOGGING_DIR 日志文件存放目录 LOGGING_DIR = "logs" # 日志存放路径 if not os.p ...

  7. 学习ASP.NET Core(10)-全局日志与xUnit系统测试

    上一篇我们介绍了数据塑形,HATEOAS和内容协商,并在制器方法中完成了对应功能的添加:本章我们将介绍日志和测试相关的概念,并添加对应的功能 一.全局日志 在第一章介绍项目结构时,有提到.NET Co ...

  8. .NET跨平台之旅:增加文件日志功能遇到的挫折

    在将我们的ASP.NET 5示例站点(about.cnblogs.com)升级至ASP.NET 5 RC1的时候,我们增加了控制台日志功能. 在ASP.NET 5添加日志功能很简单,只需在projec ...

  9. 为.NET Core项目定义Item Template

    作为这个星球上最强大的IDE,Visual Studio不仅仅提供了很多原生的特性,更重要的是它是一个可定制的IDE,比如自定义Project Template和Item Template就是一个非常 ...

随机推荐

  1. 数据库-SQL语句:删除和修改语句-列类型-列约束

    使用MySQL客户端连接服务器的两种方式: (1)交互模式: ——查 mysql.exe  -h127.0.0.1  -uroot  -p mysql   -uroot (2)脚本模式:——增删改 m ...

  2. More x64 assembler fun-facts–new assembler directives(转载)

    原文地址 The Windows x64 ABI (Application Binary Interface) presents some new challenges for assembly pr ...

  3. 在Unity5.6.5f1中使用C#7语法

    备忘,记忆力越来越差了,必需把这种琐碎的东西记下来,以防1年后想再用完全没头绪. 之前试过用C#6语法,但是怎么配置操作的完全没印象了. 首先去这下载扩展 https://bitbucket.org/ ...

  4. boost--日期处理

    1.timer 不同于系统函数的timer()一般生成一个定时器,boost中的timer是一个计时器,以秒为单位,最小精度为毫秒,使用需要包含头文件"boost\timer.hpp&quo ...

  5. python运算符优先级

    下面这个表给出Python的运算符优先级,从最低的优先级(最松散地结合)到最高的优先级(最紧密地结合).这意味着在一个表达式中,Python会首先计算表中较下面的运算符,然后在计算列在表上部的运算符. ...

  6. Redis Sentinel 模拟故障迁移

    什么是redis sentinel 参考文档:https://redis.io/topics/sentinel 简单的来说,就是Redis Sentinel 为redis 提供高可用性,主要体现在下面 ...

  7. Alpha冲刺 - (4/10)

    Alpha冲刺 - (4/10)   Part.1 开篇 队名:彳艮彳亍团队 组长博客:戳我进入 作业博客:班级博客本次作业的链接 Part.2 成员汇报 组员1(组长)柯奇豪 过去两天完成了哪些任务 ...

  8. 冲刺博客NO.9

    今天做了什么: 看书,看视频学UI设计,尝试设计并美化,然并没有美感,感觉自己设计的界面太丑. 主体进度差不多完成了,美化.

  9. docker rmi命令-删除image

    rmi 删除image Usage: docker rmi IMAGE [IMAGE...]Remove one or more images -f,--force=falseForce remova ...

  10. 带你走进CSS定位详解

    学习CSS相关知识,定位是其中的重点,也是难点之一,如果不了解css定位有时候都不知道怎么用,下面整理了一下关于定位属性的具体理解和应用方案. 一:定位 定位属性列表 position top bot ...