PostgreSQL
 sql >> база данни >  >> RDS >> PostgreSQL

.NET Core регистриране в PostgreSQL DB с помощта на NLog

Това ми помогна да пиша във файл и PostgreSQL:

  1. Първо създадох уеб приложение ASP.NET Core (.NET Core).
  2. След това инсталирах от NuGet:

  3. Модифицира следните файлове по този начин:

    а) project.json

    "buildOptions": {
        "emitEntryPoint": true,
        "preserveCompilationContext": true,
        "copyToOutput": {
            "includeFiles": [ "nlog.config" ]
        }
    },
    "publishOptions": {
        "include": [
            "wwwroot",
            "web.config",
            "nlog.config"
        ]
    }
    


    б) Startup.cs

    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            env.ConfigureNLog("nlog.config");
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            app.UseDeveloperExceptionPage();
            app.UseMvc();
            app.AddNLogWeb();
        }
    }
    


    в) 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="c:\temp\internal-nlog.txt">
    
      <!-- Load the ASP.NET Core plugin -->
      <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
      </extensions>
    
      <!-- the targets to write to -->
      <targets>
        <target xsi:type="File" name="localFile" fileName="c:\\temp\\nlog-all-${shortdate}.log"
                 layout="${longdate} ${level} ${message} ${logger} ${callsite} ${exception:format=tostring}" />
    
        <target name="database" xsi:type="Database">
          <dbProvider>Npgsql.NpgsqlConnection, Npgsql, Version=3.2.1.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7</dbProvider>
          <connectionString>Server=localhost;Port=5432;User Id=XXX;Password=XXX;Database=TestLog;</connectionString>
          <commandText>
            insert into "logs" ("Application", "Timestamp", "Level", "Message", "Logger", "CallSite", "Exception")
            values (:Application, :Timestamp, :Level, :Message, :Logger, :Callsite, :Exception);
          </commandText>
          <parameter name="@Application" layout="TestApp" />
          <parameter name="@Timestamp" layout="${longdate}" />
          <parameter name="@Level" layout="${level}" />
          <parameter name="@Message" layout="${message}" />
          <parameter name="@Logger" layout="${logger}" />
          <parameter name="@Callsite" layout="${callsite}" />
          <parameter name="@Exception" layout="${exception:format=tostring}" />
        </target>
    
        <!-- write to the void aka just remove -->
        <target xsi:type="Null" name="blackhole" />
      </targets>
    
      <!-- rules to map from logger name to target -->
      <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Debug" writeTo="database" />
        <logger name="*" minlevel="Debug" writeTo="localFile" />
    
        <!--Skip Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
      </rules>
    </nlog>
    


    г) Контролер

    public class HomeController : Controller
    {
        ILogger<HomeController> _logger;
    
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
    
        [Route("home/test")]
        public IActionResult Test()
        {
            _logger.LogInformation("Logged test information from home controller.");
    
            return Ok("Ok");
        }
    }
    


Използвана литература:
[1]. Първи стъпки с ASP.NET Core (project.json)



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Връщане на списък с часови зони, поддържани от PostgreSQL

  2. UPDATE с jsonb_set() засяга само един обект във вложен масив

  3. Вземете броя на дните в месеца в PostgreSQL

  4. Как да изчистите и преинсталирате postgresql на ubuntu?

  5. Проблем с accepts_nested_attributes_for в Rails 5.0.0.beta3, -api опция