关于.Net 6 添加NLog的方法

创建一个.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:00:28.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);
        #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);
        #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);
        #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);
    }
}

添加测试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,运行测试

到此这篇关于.Net 6 添加NLog的文章就介绍到这了,更多相关.Net 6 添加NLog内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 通过.NET 6实现RefreshToken

    目录 需求 目标 原理与思路 实现 使ApplicationUser支持RefreshToken 修改CreateToken签名使其同时返回Refresh Token 修改login方法 实现refresh token接口 实现refresh token功能 验证 总结 需求 在上一篇文章使用.NET 6实现基于JWT的Identity功能中,我们演示了如何使用.NET框架的Identity组件实现基于JWT Token的认证和授权功能.我们可以想象一下场景:当获取到的Token过期以后,我们必

  • .Net 6中的PeriodTimer介绍

    .net 6中新增了一个异步计时器PeroidTimer,相对普通Timer的回调, 它的模型更简单. var       second = TimeSpan.FromSeconds(3);  using var timer  = new PeriodicTimer(second); while (await timer.WaitForNextTickAsync()) {     Console.WriteLine($"Tick {DateTime.Now}"); } 关于WaitFo

  • .NET 6开发之实现缓存过程详解

    目录 需求 目标 原理与思路 实现 使用原生ResponseCaching实现缓存 使用Marvin.Cache.Headers实现更多缓存功能 一点扩展 总结 参考资料 需求 有的时候为了减少客户端请求相同资源的逻辑重复执行,我们会考虑使用一些缓存的方式,在.NET 6中,我们可以借助框架提供的中间件来实现请求资源的缓存. 目标 实现请求结果的缓存. 原理与思路 对于在.NET6中实现缓存,我们可以使用响应缓存中间件ResponseCaching来实现,同时可以使用Marvin.Cache.H

  • 关于.Net 6 添加NLog的方法

    创建一个.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.

  • AngularJS实现动态添加Option的方法

    本文实例讲述了AngularJS实现动态添加Option的方法.分享给大家供大家参考,具体如下: 项目中后台管理设置,前台下拉动态添加option <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge&q

  • python编程之requests在网络请求中添加cookies参数方法详解

    哎,好久没有学习爬虫了,现在想要重新拾起来.发现之前学习爬虫有些粗糙,竟然连requests中添加cookies都没有掌握,惭愧.废话不宜多,直接上内容. 我们平时使用requests获取网络内容很简单,几行代码搞定了,例如: import requests res=requests.get("https://cloud.flyme.cn/browser/index.jsp") print res.content 你没有看错,真的只有三行代码.但是简单归简单,问题还是不少的. 首先,这

  • thinkPHP5实现数据库添加内容的方法

    本文实例讲述了thinkPHP5实现数据库添加内容的方法.分享给大家供大家参考,具体如下: 面对一个新框架安装好了一般不知道要干啥.那就先做一个写入功能先. 先做好准备工作先,首先要连接上数据库. 配置文件在application下的database.php里 return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'shoptest', // 用户名 '

  • javascript 动态脚本添加的简单方法

    异步加载js文件或者异步加载js模块,支持所有浏览器,包括IE,参考至javascript高级编程 1.createScript方法用于创建一个script标签并添加到body标签中 2.createModule方法用于创建一个script脚本的标签,并且如果在IE8以下的版本运行会抛出异常,在异常捕获模块中执行script.text兼容IE添加js的脚本内容. <button id="demo">js文件</button> <button id=&quo

  • js给selected添加options的方法

    本文实例讲述了js给selected添加options的方法.分享给大家供大家参考.具体实现方法如下: <select id="Mmonth"> <option>1</option> </select> <input type="button" onclick="a()" value="添加"/> <script> function a(){ docume

  • pymongo为mongodb数据库添加索引的方法

    本文实例讲述了pymongo为mongodb数据库添加索引的方法.分享给大家供大家参考.具体实现方法如下: from pymongo import ASCENDING, DESCENDING posts.create_index([("date", DESCENDING), ("author", ASCENDING)]) 返回: u'date_-1_author_1' 希望本文所述对大家的Python程序设计有所帮助.

  • jquery实现Li滚动时滚动条自动添加样式的方法

    本文实例讲述了jquery实现Li滚动时滚动条自动添加样式的方法.分享给大家供大家参考.具体如下: 这里使用jquery实现当拖动滚动条的时候,Li滚动列表中的内容会自动随滚动条变化而下移,并自动添加样式. 运行效果截图如下: 具体代码如下: <html lang="en"> <head> <meta charset="utf-8"> <title>scroll滚动,LI随滚动条自动变化</title> &

  • jQuery为动态生成的select元素添加事件的方法

    项目中需要在点击按钮时动态生成select元素,为防止每次点击按钮时从服务器端获取数据(因为数据都是相同的),可以这样写代码 1.首先定义全局js变量 var strVoucherGroupSelect =""; 2.在js中写好获取服务端数据的代码 function genVoucherGroupSelect(rowID){ return $(strVoucherGroupSelect).attr("id", "sl_" + rowID).pa

  • JS脚本实现动态给标签控件添加事件的方法

    本文实例讲述了JS脚本实现动态给标签控件添加事件的方法.分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> &l

随机推荐