ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.Net 6 添加NLog

2022-01-21 18:32:10  阅读:127  来源: 互联网

标签:logger string app args 添加 NLog msg Net public


创建一个.Net 6 Demo项目

引入NLog包

 添加项目配置文件nlog.config

<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true" >

    <!-- the targets to write to -->
    <targets>

        <!--单个文件过大会导致写入效率下降,可配置单个文件的最大容量-->
        <target name="File" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
            <target xsi:type="File"
                    fileName="${basedir}/logs/${shortdate}.log"
                    layout="${date:yyyy-MM-dd HH\:mm\:ss} ${level:uppercase=true} ${event-context:item=Action} ${message} ${event-context:item=Amount} ${stacktrace}"
                    archiveAboveSize="10240"
                    archiveEvery="Day"
                    />
        </target>

        <!-- write logs to file -->
        <!--<target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log"
                layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />-->
        <!--<target xsi:type="Console" name="logconsole"
                layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />-->
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
        <!--<logger name="*" levels="Debug,Info,Warn,Error" writeTo="File" />-->
        <logger name="*" minlevel="Debug" maxlevel="Error" writeTo="File" />
    </rules>
</nlog>

layout布局:

${longdate} 格式:2022-01-21 17:54:01.4860

后面的毫秒不是我想要的,可以自定义:date:yyyy-MM-dd HH\:mm\:ss

 

NLog等级

Trace:最常见的记录信息,一般是普通输出

Debug:同样是记录信息,出现的频率比Trace少,一般是调试程序

Info:信息类型的消息

Warn:警告消息

Error:错误消息

自上而下,等级递增

指定特定等级:level="Warn"

指定多个等级:levels="Debug,Info" 以逗号分隔

指定等级范围:minlevel="Info" maxlevel="Error"

<rules>
    <!--<logger name="*" levels="Debug,Info,Warn,Error" writeTo="File" />-->
    <logger name="*" minlevel="Debug" maxlevel="Error" writeTo="File" />
</rules> 

添加工具类 Logger

using NLog;

namespace TestNet6.Utilities
{
    public class Logger
    {
        NLog.Logger _logger { get; set; }

        private Logger(NLog.Logger logger)
        {
            _logger = logger;
        }

        public Logger(string name) : this(LogManager.GetLogger(name))
        {

        }

        public static Logger Default { get; private set; }

        static Logger()
        {
            Default = new Logger(LogManager.GetCurrentClassLogger());
        }

        #region Dedub

        public void Debug(string msg, params object[] args)
        {
            _logger.Debug(msg, args);
        }

        public void Debug(string msg, Exception e)
        {
            _logger.Debug(e, msg);
        }

        #endregion

        #region Info

        public void Info(string msg, params object[] args)
        {
            _logger.Info(msg, args);
        }

        public void Info(string msg, Exception e)
        {
            _logger.Info(e, msg);
        }

        #endregion

        #region Trace

        public void Trace(string msg, params object[] args)
        {
            _logger.Trace(msg, args);
        }

        public void Trace(string msg, Exception e)
        {
            _logger.Trace(e, msg);
        }

        #endregion

        #region Warn

        public void Warn(string msg, params object[] args)
        {
            _logger.Warn(msg, args);
        }

        public void Warn(string msg, Exception e)
        {
            _logger.Warn(e, msg);
        }

        #endregion

        #region Error

        public void Error(string msg, params object[] args)
        {
            _logger.Error(msg, args);
        }

        public void Error(string msg, Exception e)
        {
            _logger.Error(e, msg);
        }

        #endregion
    }
}

 添加测试Controller

using Microsoft.AspNetCore.Mvc;
using TestNet6.Utilities;

namespace TestNet6.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public string Test()
        {
            Logger.Default.Info("", Request);
            return "Test String";
        }
    }
}

最后为了路由有效,还需要添加路由映射

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

//添加路由映射
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

OK,运行测试

标签:logger,string,app,args,添加,NLog,msg,Net,public
来源: https://www.cnblogs.com/linjunjieofchina/p/15831357.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有