C# NLOG无法使用.NetCore 2.2在Oracle数据库中记录用户名和会话ID
几天前我开始使用NLog,几乎实现了我需要的所有目标,除了将用户名和会话Id登录到日志文件或数据库中 我通过appsetings.json对其进行了如下配置:C# NLOG无法使用.NetCore 2.2在Oracle数据库中记录用户名和会话ID,c#,configuration,nlog,C#,Configuration,Nlog,几天前我开始使用NLog,几乎实现了我需要的所有目标,除了将用户名和会话Id登录到日志文件或数据库中 我通过appsetings.json对其进行了如下配置: "NLog": { "autoReload": true, "throwConfigExceptions": true, "internalLogLevel": "info", "internalLogFile": "c:/app/log/dev/internal-appsetting-nlog.t
"NLog": {
"autoReload": true,
"throwConfigExceptions": true,
"internalLogLevel": "info",
"internalLogFile": "c:/app/log/dev/internal-appsetting-nlog.txt",
"extensions": [
{ "assembly": "NLog.Extensions.Logging" },
{ "assembly": "NLog.Web.AspNetCore" }
],
"variables": {
"var_logdir": "c:/app/log/dev"
},
"default-wrapper": {
"type": "AsyncWrapper",
"overflowAction": "Block"
},
"targets": {
"all-file": {
"type": "File",
"fileName": "${var_logdir}/nlog-all-${shortdate}.log",
"layout": {
"type": "JsonLayout",
"Attributes": [
{
"name": "timestamp",
"layout": "${longdate}"
},
{
"name": "level",
"layout": "${level}"
},
{
"name": "logger",
"layout": "${logger}"
},
{
"name": "message",
"layout": "${message:raw=true}"
},
{
"name": "properties",
"encode": false,
"layout": {
"type": "JsonLayout",
"includeallproperties": "true"
}
},
{
"name": "username",
"layout": "${aspnet-user-identity}"
}
]
}
},
"db": {
"type": "Database",
//"commandText": "INSERT INTO myOracleLogTable (LOG_TRACETIME, LOG_LOGLEVEL, LOG_LOGGER, LOG_MESSAGE, LOG_MACHINENAME, LOG_USERNAME, LOG_CALLSITE, LOG_EXCEPTIONMESSAGE, LOG_STACKTRACE, LOG_SESSIONID) VALUES (TO_TIMESTAMP(:pTRACETIME, 'YYYY-MM-DD HH24:MI:SS.FF'), :pLEVEL, :pLOGGER, :pMESSAGE, :pMACHINENAME, :pUSERNAME, :pCALLSITE, :pEXCEPTIONMESSAGE, :pSTACKTRACE, :pSESSIONID)",
"commandText": "INSERT INTO myOracleLogTable (LOG_TRACETIME, LOG_LOGLEVEL, LOG_LOGGER, LOG_MESSAGE, LOG_MACHINENAME, LOG_USERNAME, LOG_CALLSITE, LOG_THREADID, LOG_EXCEPTIONMESSAGE, LOG_STACKTRACE, LOG_SESSIONID) VALUES (TO_TIMESTAMP(:pTRACETIME, 'YYYY-MM-DD HH24:MI:SS.FF'),:pLEVEL,:pLOGGER,:pMESSAGE,:pMACHINENAME, :pUSERNAME, :pCALLSITE,:pTHREADID,:pEXCEPTIONMESSAGE,:pSTACKTRACE, :pSESSIONID)",
"parameters": [
{
"name": "TRACETIME",
"layout": "${longdate}"
},
{
"name": "@pLEVEL",
"layout": "${level}"
},
{
"name": "@pLOGGER",
"layout": "${logger}"
},
{
"name": "@pMESSAGE",
"layout": "${message}"
},
{
"name": "@pMACHINENAME",
"layout": "${machinename}"
},
{
"name": "@pUSERNAME",
"layout": "${aspnet-user-identity}"
},
{
"name": "@pCALLSITE",
"layout": "${callsite:filename=true}"
},
{
"name": "@pTHREADID",
"layout": "${threadid}"
},
{
"name": "@pEXCEPTIONMESSAGE",
"layout": "${exception}"
},
{
"name": "@pSTACKTRACE",
"layout": "${stacktrace}"
},
{
"name": "@pSESSIONID",
"layout": "${aspnet-sessionid}"
}
],
"dbProvider": "Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess",
"connectionString": "${configsetting:name=appSettings.DefaultDataBase}"
}
},
"rules": [
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "all-file"
},
{
"logger": "Microsoft.*",
"minLevel": "Warn",
"writeTo": "db"
},
{
"logger": "MyController",
"minLevel": "Trace",
"writeTo": "db"
},
{
"logger": "RequestResponseLoggingMiddleware",
"minLevel": "Info",
"writeTo": "db"
},
{
"logger": "ExceptionHandlerMiddleware",
"minLevel": "Info",
"writeTo": "db"
}
]
},
Program.cs:
public static class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
//Read configuration from appsettings.json
config
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
//Add environment variables to config
config.AddEnvironmentVariables();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddDebug();
logging.AddConsole();
logging.AddNLog();
});
}
公共静态类程序
{
公共静态void Main(字符串[]args)
{
CreateWebHostBuilder(args.Build().Run();
}
公共静态IWebHostBuilder CreateWebHostBuilder(字符串[]args)=>
WebHost.CreateDefaultBuilder(args)
.UseStartup()
.ConfigureAppConfiguration((hostingContext,config)=>
{
var env=hostingContext.HostingEnvironment;
//从appsettings.json读取配置
配置
.AddJsonFile(“appsettings.json”,可选:true,重载更改:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,
可选:true,重载更改:true);
//将环境变量添加到配置中
config.AddEnvironmentVariables();
})
.ConfigureLogging(日志=>
{
logging.ClearProviders();
logging.AddDebug();
logging.AddConsole();
logging.AddNLog();
});
}
Startup.cs:
using Core.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using Microsoft.AspNetCore.Identity;
using Core.Interfaces;
using Core.Services.Helpers;
using Newtonsoft.Json;
using Core.Domain.Models;
using System.Collections.Generic;
using ApiAppExchange.ActionFilter;
namespace ApiAppExchange
{
public class Startup
{
public IConfiguration Configuration { get; }
string title
{
get
{
return Configuration.GetValue<string>("appSettings:Title");
}
}
string version
{
get
{
return Configuration.GetValue<string>("appSettings:Version");
}
}
string description
{
get
{
return Configuration.GetValue<string>("appSettings:Description");
}
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
var appsettings = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
LogManager.Configuration = new NLogLoggingConfiguration(configuration.GetSection("NLog"));
Configuration = appsettings.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new LogAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddHttpClient(Configuration.GetValue<string>("Client:clientName"), client =>
{
client.BaseAddress = new Uri(Configuration.GetValue<string>("Client:OAuthTokenUrl"));
client.Timeout = new TimeSpan(0, 0, Configuration.GetValue<int>("Client:TimeOut"));
});
services.AddOptions();
services.AddClientClient(Configuration.GetSection("Client"));
services.AddMajorelDBRepository(Configuration.GetSection("appSettings"));
services.AddScoped<LogAttribute>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(version, new Info
{
Version = version,
Title = title,
Description = description
});
//Locate the XML file being generated by ASP.NET...
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//... and tell Swagger to use those XML comments.
c.IncludeXmlComments(xmlPath);
});
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddDefaultTokenProviders()
.AddDefaultUI();
}
// 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, IDBRepository dBRepository)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.UseMiddleware<ExceptionHandlerMiddleware>();
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{title}-{version}");
});
try
{
NLogConfigurationHelper.ConfigureLoggerFromDatabase(dBRepository, this.Configuration.GetValue<string>("appSettings:Name"));
}
catch (Exception exception)
{
string message = JsonConvert.SerializeObject(new returnResult
{
innerStatus = EReturnValue.KO,
messages = new List<message>()
{ new message()
{ code=new errorCode().technicalError.code,
description = $"{new errorCode().technicalError.description} : {exception.Message}",
field =exception.Source
}
}
});
}
}
}
}
使用核心中间件;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用swashback.AspNetCore.Swagger;
使用制度;
使用System.IO;
运用系统反思;
使用Microsoft.Extensions.Logging;
使用NLog;
使用NLog.Extensions.Logging;
使用Microsoft.AspNetCore.Identity;
使用核心接口;
使用Core.Services.Helpers;
使用Newtonsoft.Json;
使用Core.Domain.Models;
使用System.Collections.Generic;
使用ApiAppExchange.ActionFilter;
名称空间ApiAppExchange
{
公营创业
{
公共IConfiguration配置{get;}
字符串标题
{
得到
{
返回Configuration.GetValue(“appSettings:Title”);
}
}
字符串版本
{
得到
{
返回Configuration.GetValue(“appSettings:Version”);
}
}
字符串描述
{
得到
{
返回Configuration.GetValue(“appSettings:Description”);
}
}
公共启动(IConfiguration配置)
{
配置=配置;
var appsettings=new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(“appsettings.json”);
LogManager.Configuration=newnlogloggingconfiguration(Configuration.GetSection(“NLog”);
Configuration=appsettings.Build();
}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddMvc(选项=>
{
options.Filters.Add(新的LogAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddHttpClient(Configuration.GetValue(“Client:clientName”),Client=>
{
client.BaseAddress=新Uri(Configuration.GetValue(“客户端:OAuthTokenUrl”);
client.Timeout=newtimespan(0,0,Configuration.GetValue(“client:Timeout”));
});
services.AddOptions();
services.AddClientClient(Configuration.GetSection(“客户端”));
services.addmajoreldbrespository(Configuration.GetSection(“appSettings”));
services.addScope();
services.AddSwaggerGen(c=>
{
c、 SwaggerDoc(版本,新信息
{
版本=版本,
头衔,
描述=描述
});
//找到由ASP.NET生成的XML文件。。。
var xmlFile=$“{Assembly.getExecutionGassembly().GetName().Name}.XML”;
var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile);
//…并告诉Swagger使用这些XML注释。
c、 includexmlcoments(xmlPath);
});
服务.额外性()
.AddRoles()
.AddDefaultTokenProviders()
.AddDefaultUI();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void Configure(IApplicationBuilder应用程序、IHostingEnvironment环境、ILoggerFactory loggerFactory、IDBRepository dBRepository)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseMiddleware();
app.UseMiddleware();
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c=>
{
c、 SwaggerEndpoint($“/swagger/{version}/swagger.json”,$“{title}-{version}”);
});
尝试
{
NLOGConfiguration Helper.ConfigureLoggerFromDatabase(dBRepository,this.Configuration.GetValue(“appSettings:Name”);
}
捕获(异常)
{
string message=JsonConvert.SerializeObject(新返回器