系列目录

循序渐进学.Net Core Web Api开发系列目录

本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi

一、本篇概述

本篇介绍日志的使用,包括系统默认的控制台日志和第三方NLog日志管理。

二、使用系统控制台日志

1、使用内置日志

    [Produces("application/json")]
[Route("api/Article")]
public class ArticleController : Controller
{ private readonly ILogger _logger;
public ArticleController(SalesContext context, ILogger<ArticleController> logger)
{
_logger = logger;
} [HttpGet("logger")]
public void TestLogger()
{
_logger.LogCritical("LogCritical");
_logger.LogError("LogError");
_logger.LogWarning("LogWarning");
_logger.LogInformation("LogInformation");
_logger.LogDebug("LogDebug"); return;
}
}

默认只能看到前三条记录:

主要原因是日志的最低级别默认为Warring,如果要显示其他级别日志,需要修改application.json文件。

{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Error"
}
},
"Console": {
"LogLevel": {
"Default": "Information"
}
}
}
}

日志级别优先级如下顺序:

Critical > Error > Warning > Information > Debug

调整日志级别为Information 或Debug以后会显示太多无关的日志信息,可以配置默认级别为Warring,而自己项目命名空间的日志级别为Debug。

"Console": {
"LogLevel": {
"Default": "Warning",
"SaleService.Controllers": "DEBUG"
}
}

2、几点说明

1)目前日志已经可以正常工作了,把项目发布到Linux环境下,通过配置Supervisor可以把控制台的内容输出到文件系统,建议在调试环境下采用Debug日志级别,而在生成环境采用Error日志级别。配置Supervisor的内容可以参考:循序渐进学.Net Core Web Api开发系列【7】:项目发布

2)如果稍微了解依赖注入(DI)的知识,就可以理解我们在Controoler中使用ILogger是采用标准的构造函数注入的方式,但是问题是用户并没有注册该服务,其实是系统在CreateDefaultBuilder时帮我们注册了日志服务。可以看几段源码的片段:

CreateDefaultBuilder:
using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore
{
public static class WebHost
{
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
return WebHostBuilderIISExtensions.UseIISIntegration(HostingAbstractionsWebHostBuilderExtensions.UseContentRoot(WebHostBuilderKestrelExtensions.UseKestrel(new WebHostBuilder()), Directory.GetCurrentDirectory()).ConfigureAppConfiguration(delegate(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
{
IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
JsonConfigurationExtensions.AddJsonFile(JsonConfigurationExtensions.AddJsonFile(config, "appsettings.json", true, true), string.Format("appsettings.{0}.json", hostingEnvironment.EnvironmentName), true, true);
if (HostingEnvironmentExtensions.IsDevelopment(hostingEnvironment))
{
Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
if (assembly != null)
{
UserSecretsConfigurationExtensions.AddUserSecrets(config, assembly, true);
}
}
EnvironmentVariablesExtensions.AddEnvironmentVariables(config);
if (args != null)
{
CommandLineConfigurationExtensions.AddCommandLine(config, args);
}
}).ConfigureLogging(delegate(WebHostBuilderContext hostingContext, ILoggingBuilder logging)
{
LoggingBuilderExtensions.AddConfiguration(logging, hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})).UseDefaultServiceProvider(delegate(WebHostBuilderContext context, ServiceProviderOptions options)
{
options.ValidateScopes = HostingEnvironmentExtensions.IsDevelopment(context.HostingEnvironment);
});
}
}
}
AddConsole:
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Console; namespace Microsoft.Extensions.Logging
{
public static class ConsoleLoggerExtensions
{
public static ILoggingBuilder AddConsole(this ILoggingBuilder builder)
{
builder.Services.AddSingleton<ILoggerProvider, ConsoleLoggerProvider>();
return builder;
}
}
}

三、使用NLog

1、通过NuGet获取包:NLog.Web.AspNetCore

2、修改Startup类的Configure方法:

 public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
loggerFactory.ConfigureNLog("nlog.config"); //如果采用默认配置文件nlog.config,该语句可以省略
}
}

nlog.config配置文件内容如下:

<?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">
<targets>
<target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}_all.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="debugfile" fileName="${basedir}/logs/${shortdate}_debug.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="errfile" fileName="${basedir}/logs/${shortdate}_error.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
</targets>
<rules>
<logger name="*" level="Debug" writeTo="debugfile" />
<logger name="*" level="Error" writeTo="errfile" />
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>

项目发布时修改配置文件,只保留errfile即可。

以上就是全部代码,Controller中的代码无需修改。

3、两个注意点

1)目前我们已经采用NLog来进行日志的记录,此时系统默认的日志仍然是正常工作的,项目发布时建议把系统默认的日志级别改成Error,nlog的输出日志只保留errfile,以免造成服务器磁盘空间浪费。

2)项目发布时nlog.config文件可能不会发布到目标目录,需要修改该文件的文件属性:

循序渐进学.Net Core Web Api开发系列【10】:使用日志的更多相关文章

  1. 循序渐进学.Net Core Web Api开发系列【0】:序言与目录

    一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...

  2. 循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 应用安全除 ...

  3. 循序渐进学.Net Core Web Api开发系列【15】:应用安全

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍W ...

  4. 循序渐进学.Net Core Web Api开发系列【14】:异常处理

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍异 ...

  5. 循序渐进学.Net Core Web Api开发系列【13】:中间件(Middleware)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  6. 循序渐进学.Net Core Web Api开发系列【12】:缓存

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  7. 循序渐进学.Net Core Web Api开发系列【11】:依赖注入

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  8. 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇描述一 ...

  9. 循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇讨论如 ...

随机推荐

  1. Linux上查看文件大小的用法(转载)

    具体用法可以参考:https://blog.csdn.net/linfanhehe/article/details/78560887 当磁盘大小超过标准时会有报警提示,这时如果掌握df和du命令是非常 ...

  2. java基础知识代码-------枚举类型

    package com.mon10.day22; /** * 类说明 :枚举类型,案例二 * * @author 作者 : chenyanlong * @version 创建时间:2017年10月22 ...

  3. OpenStack 存储服务 Cinder存储节点部署LVM(十六)

    Cinder存储节点部署 部署在192.168.137.12主机 1.安装lvm2软件包 yum install lvm2 -y 2.启动LVM的metadata服务并且设置该服务随系统启动 syst ...

  4. MySQL的DML常用语法格式

    MySQL的DML常用语法格式 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们知道MySQL的查询大致分为单表查询,多表查询以及联合查询.多表查询,顾名思义,就是查询的结果可能 ...

  5. Linux-Xshell会话保持

    1.Xshell客户端设置 2.服务端设置 修改/etc/ssh/sshd_config文件,找到 ClientAliveInterval 0和ClientAliveCountMax 3并将注释符号( ...

  6. RESTful记录-RESTful服务

    按照REST架构,一个RESTful Web服务不应该继续服务器的客户端的状态.这种限制被称为无状态.它负责客户以它的上下文传递给服务器,然后服务器可以存储这样的上下文,以处理客户端的进一步请求.例如 ...

  7. oracle connect by用法篇 (转)

    1.基本语法 select * from table [start with condition1] connect by [prior] id=parentid 1 2 1 2 一般用来查找存在父子 ...

  8. python 入门基础4 --数据类型及内置方法

    今日目录: 零.解压赋值+for循环 一. 可变/不可变和有序/无序 二.基本数据类型及内置方法 1.整型 int 2.浮点型float 3.字符串类型 4.列表类型 三.后期补充内容 零.解压赋值+ ...

  9. 【比赛游记】NOIP2017游记

    身为FJ的选手,在师大附中AHSOFNU考试,环境很不错,考得也还可以吧...[考的并不好] 不过比赛前都在划水233333 另:看到这篇博客的OIer们一定要评论啊! Day1的中午,因为穿了短袖去 ...

  10. Android启动过程

    1.背景知识                                                          Init进程是Linux环境下非常重要的一个进程,而Zygote进程是J ...