.net6使用Nlog

NLog

安装NuGet(NLog.Web.AspNetCore)

添加一个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="false"
      internalLogLevel="Off" internalLogFile="E:\temp\nlog-internal.log">
	<targets>
    //保存在E:\学习文档\C#\Nlog\WebApplication1\WebApplication1\bin\Debug\net6.0\logs
	<target xsi:type="File" name="f" fileName="logs/${var:cuspath}nlog-all-${shortdate}.log"
                //layout是格式
                layout="${longdate} ${uppercase:${level}} ${message}" />
	</targets>>
	<rules>
		<!--Skip Microsoft logs and so log only own logs-->
		<!--以Microsoft打头的日志将进入此路由,由于此路由没有writeTo属性,所有会被忽略-->
		<!--且此路由设置了final,所以此路由被匹配到了不会再继续往下匹配。未匹配到的会继续匹配下一个路由-->
		<logger name="Microsoft.*" minlevel="Trace"  final="true" />
		<logger name="*" minlevel="Debug" writeTo="f" />
	</rules>
</nlog>

在progarm.cs中配置

using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.Extensions.Hosting;
using NLog.Extensions.Logging;
using NLog.Web;
using WebApplication1.Model;

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            Configure(builder);

            var app = builder.Build();

            Configution(app);
        }

        public static void Configure(WebApplicationBuilder builder)
        {
            // Add services to the container.
            builder.Services.AddControllersWithViews();

            //Configuration
            builder.Services.AddMvcCore().AddMvcOptions(option =>
            {
                option.EnableEndpointRouting = false;
            });
            //依赖注入
            builder.Services.AddScoped<UserResitory, UserResitory>();

            builder.WebHost.ConfigureLogging((hostingcontent, logger) =>
            {
                logger.AddConfiguration(hostingcontent.Configuration.GetSection("Logger"));
                logger.AddConsole();
                logger.AddDebug();
                logger.AddNLog();
            });
        }

        public static void Configution(WebApplication app) 
        {
            //判断用户
            if (app.Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}");
            //app.MapGet("/", () => "Hello World!");
            app.Run();
        }
    }
}

homecontroller.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;

namespace WebApplication1.Controllrt
{
    public class HomeController : Controller
    {
        public ILogger<HomeController> logger;
        public ILoggerFactory loggerFactory;

        //依赖注入
        public HomeController(ILogger<HomeController> logger, ILoggerFactory loggerFactory)
        {
            this.logger = logger;
            logger.LogInformation($"{this.GetType().FullName} 被构造.... logingormation");
            logger.LogError($"{this.GetType().FullName} 被构造.... logError");
            logger.LogDebug($"{this.GetType().FullName} 被构造.... LogDebug");
            logger.LogTrace($"{this.GetType().FullName} 被构造.... LogTrace");
            logger.LogCritical($"{this.GetType().FullName} 被构造.... LogCritical");

            this.loggerFactory = loggerFactory;
            ILogger<HomeController> logger1 = loggerFactory.CreateLogger<HomeController>();
            logger1.LogCritical("这个是通过Factory得到的Logger写的日志");
        }

        // GET: HomeController
        public ActionResult Index()
        {
            return View();
        }

        // GET: HomeController/Details/5
        public ActionResult Details(int id)
        {
            logger.LogInformation($"{this.GetType().FullName} Details被请求");
            return View();
        }

        // GET: HomeController/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: HomeController/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: HomeController/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: HomeController/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: HomeController/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: HomeController/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET Core 控制台应用中使用 NLog,需要进行以下步骤: 1. 安装 NLog 包。您可以在 NuGet 包管理器中搜索 NLog 并安装它,或使用命令行: ``` dotnet add package NLog ``` 2. 在项目根目录下创建一个名为 `nlog.config` 的文件,并将以下配置复制到文件中,以启用NLog: ```xml <?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="Trace" internalLogFile="c:\temp\nlog-internal.log"> <targets> <target name="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="file" /> </rules> </nlog> ``` 这样,NLog 就会将日志写入到当前应用程序目录下的 `logs` 文件夹中,并将日志文件名设置为当前日期。 3. 在应用程序入口点中,添加 NLog 配置和日志记录: ```csharp using NLog; using NLog.Config; using NLog.Targets; class Program { static void Main(string[] args) { // 加载NLog配置 LogManager.LoadConfiguration("nlog.config"); // 创建logger var logger = LogManager.GetCurrentClassLogger(); // 记录日志 logger.Info("Hello, NLog!"); // 等待用户按下任意键退出 Console.ReadKey(); } } ``` 这样就可以在控制台应用程序中使用 NLog 记录日志了。如果您需要更多的日志记录选项,可以参考 NLog 的官方文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值