.net core 使用 NLog 记录日志

一、先创建 .net core Web 应用程序

二、程序包控制台输入以下命令行以安装 Nuget 包:

install-package Nlog
install-package 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"
       internalLogLevel="Warn"
       internalLogFile="internal-nlog.txt">
  <!--define various log targets-->
  <targets>
    <!--write logs to file-->
    <!--<target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />-->

    <target xsi:type="File" name="ownFile-web" fileName="LogFiles/${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    <!--<target xsi:type="Null" name="blackhole" />-->
  </targets>
  <rules>
    <!--All logs, including from Microsoft-->
    <!-- 记录微软所有日志,一般不开 -->
    <!--<logger name="*" minlevel="Trace" writeTo="allfile" />-->

    <!--Skip Microsoft logs and so log only own logs-->
    <!--<logger name="Microsoft.*" minlevel="Fatal" writeTo="blackhole" final="true" />-->
    <logger name="*" minlevel="Critical" writeTo="ownFile-web" />
  </rules>
</nlog>

四、修改 Startup.cs ,  其实除了引用之外, 也就是加两行代码而已:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

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

            //使用NLog作为日志记录工具
            loggerFactory.AddNLog();
            //引入Nlog配置文件
            env.ConfigureNLog("nlog.config");

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

五、修改 Controller, 输出日志:

        private ILogger<HomeController> logger;

        public HomeController(ILogger<HomeController> _logger)
        {
            logger = _logger;
        }

        public IActionResult Index()
        {
            logger.LogInformation("普通信息日志-----------");
            logger.LogDebug("调试日志-----------");
            logger.LogError("错误日志-----------");
            logger.LogCritical("异常日志-----------");
            logger.LogWarning("警告日志-----------");
            logger.LogTrace("跟踪日志-----------");
            logger.Log(LogLevel.Warning, "Log日志------------------");
            return View();
        }

日志级别:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical

日志级别由小到大, Trace 就包含了所有日志。

如果想修改日志的输出级别,应该在 nlog.config 中修改 minlevel="Trace"

试了一下, Critical 与 Fatal 的输出是一致的。

使用说明: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

详细的配置参考: https://github.com/NLog/NLog/wiki/Configuration-file

中文配置文章: http://www.cnblogs.com/fuchongjundream/p/3936431.html

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是使用NLog日志记录到SqlServer的步骤: 1. 首先,需要在项目中安装NLogNLog.Web.AspNetCore包。可以使用NuGet包管理器或在项目文件中手动添加依赖项。 2. 在项目的appsettings.json文件中添加以下NLog配置: ``` "NLog": { "targets": { "database": { "type": "Database", "dbProvider": "System.Data.SqlClient", "connectionString": "Server=[server];Database=[database];User Id=[user];Password=[password];", "commandText": "INSERT INTO [Logs] ([Date], [Level], [Logger], [Message], [Exception]) VALUES (@Date, @Level, @Logger, @Message, @Exception);", "parameter": [ { "name": "@Date", "layout": "${date}" }, { "name": "@Level", "layout": "${level}" }, { "name": "@Logger", "layout": "${logger}" }, { "name": "@Message", "layout": "${message}" }, { "name": "@Exception", "layout": "${exception}" } ] } }, "rules": [ { "logger": "*", "minLevel": "Trace", "writeTo": "database" } ] } ``` 3. 在Startup.cs文件中添加以下代码: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { //... loggerFactory.AddNLog(); //... app.UseMiddleware<NLogMiddleware>(); //... } ``` 4. 创建一个名为Logs的表,用于存储日志记录。表结构应如下所示: ```sql CREATE TABLE [dbo].[Logs]( [Id] [int] IDENTITY(1,1) NOT NULL, [Date] [datetime2](7) NOT NULL, [Level] [nvarchar](50) NOT NULL, [Logger] [nvarchar](250) NOT NULL, [Message] [nvarchar](max) NOT NULL, [Exception] [nvarchar](max) NULL, CONSTRAINT [PK_Logs] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] ``` 5. 现在,可以在代码中使用NLog记录日志了。例如: ```csharp private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("Hello, world!"); return View(); } ``` 这将在Logs表中插入一条日志记录。 希望这可以帮助到你。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值