Nlog 集成到WebApi

前言

之前的这篇文章中介绍了,桌面程序是如何使用Nlog的

Nlog 的使用_code bean的博客-CSDN博客_nlog使用${appdomain}当前应用程序域l${assembly-version}应用程序${basedir}应用程序域的基本目录。${callsite}(类名称、方法名称和相关信息的源信息)。${counter}数值${date}当前日期和时间。${environment}环境变量${exception}exception信息${guid}GUID${identity}线程标识信息${level}级别。${log4jx..https://blog.csdn.net/songhuangong123/article/details/124152443?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166756627816782427448356%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=166756627816782427448356&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-124152443-null-null.article_score_rank_blog&utm_term=Nlog&spm=1018.2226.3001.4450#:~:text=%E5%8F%91%E5%B8%83-,Nlog%20%E7%9A%84%E4%BD%BF%E7%94%A8,-code%20bean

但是如果是WebApi,有一点不同,总的来说,前期的配置工作变多了。其他的不变。

安装

首先是安装包:建议5以上版本

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"
	  autoReload="true"
	  throwExceptions="true"
	  internalLogLevel="Off" 
	  internalLogFile="Logs\internal-nlog-AspNetCore.txt">

	<targets>
		<!--控制台输出-->
		<target name="console" xsi:type="ColoredConsole" layout="${date:format=HH\:MM\:ss} ${logger} ${message}"/>
		<!--调试输出,带行号-->
		<target name="debug_file"
				xsi:type="File"
                fileName="${basedir}/Logs/${shortdate}/Debug/log.txt"
				maxArchiveFiles="30"
			layout="【${longdate}】${level:uppercase=false} ${callsite:className=True:fileName=True:includeSourcePath=False:methodName=False}:${message}" />
		<!--错误输出,带行号-->
		<target name="error_file"
				xsi:type="File"
                fileName="${basedir}/Logs/${shortdate}/log.txt"
				maxArchiveFiles="30"
                layout="【${longdate}】${level:uppercase=false} ${callsite:className=True:fileName=True:includeSourcePath=False:methodName=False}:${message}" />
    </targets>
	
    <rules>
		<logger name="System.*" finalMinLevel="Warn"/>
		<logger name="Microsoft.*" finalMinLevel="Warn"/>
		<logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info"/>

		<logger name="*" minlevel="Trace" writeTo="console" />
		<logger name="*" minlevel="Debug" writeTo="debug_file" />
		<logger name="*" minlevel="Error" writeTo="error_file" />
    </rules>
</nlog>

对Config的简单说明

autoReload="true"
在配置文件头部的这个属性,如果有True,在网站跑的过程中,可以随时变更nlog.config文件,随时生效。

throwExceptions="true"
这个前期对nlog.config文件如果有写法错误,或是项目中对日志模块有什么异常错误的话,会主动抛出来,这个对前期集成NLog模块或写配置文件时有用。

<logger name="System.*" finalMinLevel="Warn"/>
<logger name="Microsoft.*" finalMinLevel="Warn"/>
<logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info"/>

这个主要是过滤掉一些WebApi内部的一些打印信息,不然你的打印会带出来其他的一堆打印。但是程序启动的WebApi的一些内容,目前我发现过滤不掉。不过之后就没有了。

修改Program.cs

最关键的一句话

builder.Logging.AddNLog("nlog.config");

Program.cs中加入这句

这就相当于注册,为注入做准备,不然控制器里的_logger也无法输出log到文件

注入之后,控制器里直接用就好了:

控制器使用情况

Program.cs的全部内容如下:

using MySocketLib.TcpSvr;
using NLog;
using NLog.Web;



var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");


try
{

    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.

    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    //为了返回任意形式xml,需要这个,需要安装包:Microsoft.AspNetCore.Mvc.WebApiCompatShim
    builder.Services.AddMvc().AddWebApiConventions();

    builder.Logging.AddNLog("nlog.config");

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseAuthorization();

    app.MapControllers();

    //启动TCP
    TcpSvrCtrl.Run();

    app.Run();
}
catch (Exception exception)
{
    // NLog: catch setup errors
    logger.Error(exception, "Stopped program because of exception");
    throw;
}
finally
{
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    NLog.LogManager.Shutdown();
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code bean

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值