ASP.NET Core 2.0 WebApi全局配置及日誌

最新在將原來寫的一些webSerivce轉換爲WebApi,直接就用了ASP.Net Core 2.0的框架,在使用中,發現的與原有的asp.net不一樣的地方,經過搜索已經慢慢解決,記錄下來備用。web

1、全局配置數據庫

在asp.net中,全局變動配置寫在web.config中,以下所示json

 1 <?xml version="1.0"?>
 2 <configuration>
 3 <connectionStrings>
 4     <add name="conn" connectionString="Data Source=localhost;Initial Catalog=helloworld;Integrated Security=True"/>
 5   </connectionStrings>
 6   <appSettings>
 7     <add key="app_key" value="helloworld" />
 8     <add key="app_secret" value="1234567890abcdef" />
 9   </appSettings>
10 </configuration>

在ASP.Net Core 2.0 WebApi中,已經沒有了web.config文件,查了一些資料,能夠把全局變量配置寫在appsetting.json文件中,以下所示:app

{
  "connectionStrings": {
    "conn": "Data Source=localhost;Initial Catalog=helloworld;Integrated Security=True"
  }
  "appSettings": {
    "app_key": "helloworld",
    "app_secret": "1234567890abcdef"
  }
}

這樣一來,在程序中就能夠對全局變量配置進行引用了。框架

使用appSetting.json,全局變量能夠設置的更爲複雜,具體的方法能夠參考文後的參考文獻。asp.net

2、記錄日誌函數

之前ASP.NET的時候,日誌都是用Nlog進行記錄,如今轉換到了Core 2.0,也準備繼續使用Nlog,在使用中,發現和之前的有也所不一樣。ui

首先,在Nuget中獲取NLog.Web.AspNetCore包,spa

而後將startup.cs文件的代碼進行修改.net

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
//修改成
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

並在Configure函數中,加上如下語句:

loggerFactory.AddNLog();
app.AddNLogWeb();
loggerFactory.ConfigureNLog(「nlog.config」);

記得要在文件頭先引用using NLog.Web和using NLog.Extensions.Logging;

增長一個"Web配置文件",文件名爲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">
    <targets>
        <target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
        <target xsi:type="File" name="debugfile" fileName="${basedir}/logs/${shortdate}_debug.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
    <target xsi:type="File" name="errfile" fileName="${basedir}/logs/${shortdate}_error.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
  </targets>
    <rules>
    <logger name="*" level="Debug" writeTo="debugfile" />
      <logger name="*" level="Error" writeTo="errfile" />
    <logger name="*" minlevel="Trace" writeTo="logfile" />
    </rules>
</nlog>

而後在程序中就能夠開始調用日誌功能了。

二個功能的DEMO代碼以下:

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using NLog.Extensions.Logging;
using NLog.Web;

public class Program
{
    public static IConfigurationRoot Configuration { get; set; }
    public static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
    public static void ConfigAndLog()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
        string app_key = Configuration["appSettings:app_key"];
        string coon = Configuration["connectionStrings:conn"];
        log.Debug("數據庫鏈接爲:" + conn);
        return;
    }
}

參考文檔:

[1].Configure an ASP.NET Core App

[2].在 Asp.net core 2.0 的Web Api 添加logging

相關文章
相關標籤/搜索