如何在Asp.NetMVC中對Serilog進行配置-創(chuàng)新互聯(lián)

如何在Asp.Net MVC中對Serilog進行配置?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

我們提供的服務有:成都網(wǎng)站設(shè)計、成都網(wǎng)站制作、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、和碩ssl等。為近千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術(shù)的和碩網(wǎng)站制作公司

ASP.NET 是什么

ASP.NET 是開源,跨平臺,高性能,輕量級的 Web 應用構(gòu)建框架,常用于通過 HTML、CSS、JavaScript 以及服務器腳本來構(gòu)建網(wǎng)頁和網(wǎng)站。

一、Serilog介紹

Serilog 是一種非常簡便記錄log 的處理方式,使用Serilog可以生成本地的text文件, 也可以通過 Seq 來在Web界面中查看具體的log內(nèi)容。

二、配置方法

接下來就簡單的介紹一下在Asp.Net MVC中如何配置是Serilog 生效:

 1):下載并且安裝Seq,安裝到默認的路徑之后,實際上時候啟動了一個Win Service,并且監(jiān)聽的端口號默認為 5341.

安裝的最后一步截圖如下:

如何在Asp.Net MVC中對Serilog進行配置

然后我們到Service列表中可以找到對應的Service, 如下圖所示:

如何在Asp.Net MVC中對Serilog進行配置

2):創(chuàng)建一個Asp.Net MVC 5的一個工程, 然后通過 Nuget 下載并且安裝 對應的 package,如下圖所示

如何在Asp.Net MVC中對Serilog進行配置

3):在 App_Start 文件夾下創(chuàng)建一個 class 叫做 SerilogConfig.cs , 代碼如下所示

using Serilog;
using SerilogWeb.Classic.Enrichers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Hosting;

namespace TestSerilog.App_Start
{
  public class SerilogConfig
  {
    public static ILogger CreateLogger()
    {
      var logpath = HostingEnvironment.MapPath("~");
      var config = new LoggerConfiguration()
        .Enrich.WithMachineName()
        .Enrich.WithProperty("ApplicationName", AssemblyTitle)
        .Enrich.With<HttpRequestClientHostIPEnricher>()
        .Enrich.With<HttpRequestRawUrlEnricher>()
        .Enrich.With<HttpRequestIdEnricher>()
        .Enrich.With<UserNameEnricher>()
        //.Enrich.WithProperty("RuntimeVersion", Environment.Version)
        // this ensures that calls to LogContext.PushProperty will cause the logger to be enriched
        .Enrich.FromLogContext()
        .MinimumLevel.Verbose()
        .WriteTo.Seq(ConfigurationManager.AppSettings["SeqServer"], apiKey: ConfigurationManager.AppSettings["SeqApiKey"])
        .WriteTo.RollingFile(Path.Combine(logpath, "Logs\\EricSunTestLog-{Date}.log"), retainedFileCountLimit: null, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {SourceContext} - ({MachineName}|{HttpRequestId}|{UserName}) {Message}{NewLine}{Exception}");
      return config.CreateLogger();
    }

    public static string AssemblyTitle
    {
      get
      {
        var attributes = typeof(SerilogConfig).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
        if (attributes.Length > 0)
        {
          var titleAttribute = (AssemblyTitleAttribute)attributes[0];
          if (titleAttribute.Title.Length > 0)
            return titleAttribute.Title;
        }
        return Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().CodeBase);
      }
    }
  }
}

4):在 Web.config 中添加補全所用到的 appSettings

 <appSettings>
  <add key="SeqServer" value="http://localhost:5341/" />
  <add key="SeqApiKey" value="" />
 </appSettings>

5):在 Startup.cs 中添加如下代碼完成注冊

using Microsoft.Owin;
using Owin;
using Serilog;
using TestSerilog.App_Start;

[assembly: OwinStartupAttribute(typeof(TestSerilog.Startup))]
namespace TestSerilog
{
  public partial class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      ConfigureAuth(app);
      Log.Logger = SerilogConfig.CreateLogger();
    }
  }
}

6): 在 HomeController 中的 Index Action 中添加如下代碼,測試對應的Debug,Information,WarningError方法

using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TestSerilog.Controllers
{
  public class HomeController : Controller
  {
    private ILogger _logger = Log.Logger; 

    public ActionResult Index()
    {
      _logger.Debug("This is index -- debug.");
      _logger.Information("This is index -- information.");
      _logger.Warning("This is index -- warning.");
      _logger.Error("This is index -- error.");
      return View();
    }

    public ActionResult About()
    {
      ViewBag.Message = "Your application description page.";

      return View();
    }

    public ActionResult Contact()
    {
      ViewBag.Message = "Your contact page.";

      return View();
    }
  }
}

7):直接 VS 2015 運行之后, 再去http://localhost:5341/#/events中觀察對應的 log 記錄, 如下截圖

如何在Asp.Net MVC中對Serilog進行配置

看完上述內(nèi)容,你們掌握如何在Asp.Net MVC中對Serilog進行配置的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

分享名稱:如何在Asp.NetMVC中對Serilog進行配置-創(chuàng)新互聯(lián)
文章出自:http://bm7419.com/article14/didsge.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、微信小程序、定制網(wǎng)站、服務器托管企業(yè)建站、外貿(mào)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)