NLOG не может записать имя пользователя и идентификатор сеанса в базу данных Oracle, используя .NetCore 2.2 - PullRequest
0 голосов
/ 17 октября 2019

Я начал использовать NLog несколько дней назад и почти достиг всех целей, которые мне нужны, за исключением регистрации имени пользователя и идентификатора сеанса в файлах журнала или в базе данных.

Я настроил его через appsetings.json какэто:

    "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();
            });
}

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
                                                }
                                          }

                });
            }          

        }
    }
}

Последней попыткой было добавить службу AddIdentity в startuo, но это нене работаетЯ должен что-то пропустить, но я не знаю что.

Любая помощь приветствуется

С уважением

1 Ответ

1 голос
/ 21 октября 2019

это была моя ошибка. Я думаю, что у меня должны быть идентификатор пользователя и идентификатор сеанса, но я понял, что не могу, как я назвал веб-сервис, без такой идентификации ....

Так что на самом деле проблем нет.

...