.net6使用Nlog

NLog

安装NuGet(NLog.Web.AspNetCore)

添加一个NLog.config文件


<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
	
	targets>>
	<rules>
		
		
		
		<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();

            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 logger;
        public ILoggerFactory loggerFactory;

        //依赖注入
        public HomeController(ILogger 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 logger1 = loggerFactory.CreateLogger();
            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();
            }
        }
    }
}

你可能感兴趣的:(.net,.net,c#)