.Net Core NLog+oracel

简介

NLog是一个灵活且免费的日志记录平台,适用于各种.NET平台,包括.NET标准。 NLog 使写入多个目标变得容易。(数据库、文件、控制台)并动态更改日志记录配置。

引用


<ItemGroup>
    <PackageReference Include="NLog" Version="5.2.0" />
    <!-oracle需要装NLog.Database-->
    <PackageReference Include="NLog.Database" Version="5.2.0" />  
    <PackageReference Include="NLog.Web.AspNetCore" Version="5.3.0" />
    <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="3.21.100" />
</ItemGroup>

Program.cs

//var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
//logger.Debug("init main");
//nlog
builder.Logging.ClearProviders(); //删除其他日志
builder.Logging.AddNLog("Config/nlog.config");
builder.Host.UseNLog();
if (app.Environment.IsDevelopment())
{

    app.UseHsts();
}

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="true"
  internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <targets>
    <!--存到文件-->
    <target xsi:type="File" name="allfile" fileName="logs/all/nlog-all-${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile" fileName="logs/my/nlog-my-${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    <target xsi:type="Null" name="blackhole" />

    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <!--存入Oracle数据库-->
    <target name="database" xsi:type="Database"
             dbProvider="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess"
              connectionString="Data Source=192.168.1.11/orcl;user id=admin;password=123456">
      <!--这里的插入语句,注意最后不要加分号,否则会报错。另外,Oracle中需要用":",用"@"会报错-->
      <commandText>
        insert into LOGS (
        LOG_ID, LOG_APPLICATION, LOG_DATE, LOG_LEVEL, LOG_MESSAGE,
        LOGGER, LOG_CallSite, LOG_Exception
        ) values (
        SEQ_LOGID.nextval, :L_Application, :L_Date, :L_Level, :L_Message,
        :Logger, :Callsite, :L_Exception
        )
      </commandText>
      <parameter name=":L_Application" layout="Test" />
      <parameter name=":L_Date" layout="${date}" />
      <parameter name=":L_Level" layout="${level}" />
      <parameter name=":L_Message" layout="${message}" />
      <parameter name=":Logger" layout="${logger}" />
      <parameter name=":CallSite" layout="${callsite:filename=true}" />
      <parameter name=":L_Exception" layout="${exception:tostring}" />
    </target>
  </targets>

  <rules>
    <!-- add your logging rules here -->
    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--这里全部使用最高等级Trace,即可以记录所有类型日志。可以根据需要降低等级,如使用Info,则仅记录Info及以上的日志,Trace、Debug日志不记录-->
    <logger name="*" minlevel="Trace" writeTo="database" />
  </rules>
</nlog>

数据库

CREATE TABLE LOGS
   (    
   "LOG_ID" NUMBER not null primary key,
    "LOG_APPLICATION" VARCHAR2(100 BYTE), 
    "LOG_DATE" NVARCHAR2(30), 
    "LOG_LEVEL" VARCHAR2(20 BYTE), 
    "LOG_MESSAGE" VARCHAR2(1000 BYTE), 
    "LOGGER" VARCHAR2(100 BYTE), 
    "LOG_CALLSITE" VARCHAR2(200 BYTE), 
    "LOG_EXCEPTION" VARCHAR2(1000 BYTE)
   ) ;

CREATE SEQUENCE SEQ_LOGID 
INCREMENT BY 1 
MAXVALUE 9999999999999999999999999999 
MINVALUE 1 NOCACHE;

测试

using Microsoft.AspNetCore.Mvc;

namespace Cnpc.Com.Ioc.WebApp.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoggerController : ControllerBase
    {
        ILogger<LoggerController> _Logger;
        public LoggerController(ILogger<LoggerController> logger)
        {
            _Logger = logger;
            _Logger.LogInformation("666");
        }

        [HttpGet]
        public string GetTest()
        {
            _Logger.LogInformation("777");
            _Logger.LogDebug("我是debug");  
            try
            {
                throw new Exception("出错了");
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);
                throw;
            }

            return "xxx";
        }
    }
}
posted @ 2023-08-03 21:59  qfccc  阅读(64)  评论(0编辑  收藏  举报