【NLog】.net core web api使用NLog将日志存入Oracle及本地文件

1、安装NuGet包:
NLog;
NLog.Web.AspNetCore;
Oracle.ManagedDataAccess.Core;
NLog.Config(选装);

前三个NuGet包必装,Config那个选装,装上后会自动生成一个NLog.Config模板,默认生成在调试目录,需要手动将其拷贝到项目根目录。
如不装NLog.Config,可以自己新建一个xml配置文件。

2、NLog.Config配置文件内容:



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

  
    
    
    
    
    
  


建表语句:

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;

3、Program.cs:
引用命名空间:

using NLog.Web;
//在最后加.UseNLog();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup()
                .UseNLog();

4、Startup.cs:
引用命名空间:

using NLog.Extensions.Logging;
using NLog.Web;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

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

5、使用

private readonly Logger nlog = LogManager.GetCurrentClassLogger();
        // GET api/values
        [HttpGet]
        public ActionResult> Get()
        {
            nlog.Log(LogLevel.Debug, $"Debug");
            nlog.Log(LogLevel.Info, $"Info");
            try
            {
                throw new Exception($"异常");
            }
            catch (Exception ex)
            {
                nlog.Log(LogLevel.Error, ex, $"异常的附加信息");
            }
            return new string[] { "value1", "value2" };
        }

你可能感兴趣的:(.Net,Core,C#,Oracle,NLog)