资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

如何在Asp.NetMVC中对Serilog进行配置-创新互联

如何在Asp.Net MVC中对Serilog进行配置?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

我们提供的服务有:成都网站设计、成都网站制作、微信公众号开发、网站优化、网站认证、和硕ssl等。为近千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的和硕网站制作公司

ASP.NET 是什么

ASP.NET 是开源,跨平台,高性能,轻量级的 Web 应用构建框架,常用于通过 HTML、CSS、JavaScript 以及服务器脚本来构建网页和网站。

一、Serilog介绍

Serilog 是一种非常简便记录log 的处理方式,使用Serilog可以生成本地的text文件, 也可以通过 Seq 来在Web界面中查看具体的log内容。

二、配置方法

接下来就简单的介绍一下在Asp.Net MVC中如何配置是Serilog 生效:

 1):下载并且安装Seq,安装到默认的路径之后,实际上时候启动了一个Win Service,并且监听的端口号默认为 5341.

安装的最后一步截图如下:

如何在Asp.Net MVC中对Serilog进行配置

然后我们到Service列表中可以找到对应的Service, 如下图所示:

如何在Asp.Net MVC中对Serilog进行配置

2):创建一个Asp.Net MVC 5的一个工程, 然后通过 Nuget 下载并且安装 对应的 package,如下图所示

如何在Asp.Net MVC中对Serilog进行配置

3):在 App_Start 文件夹下创建一个 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()
        .Enrich.With()
        .Enrich.With()
        .Enrich.With()
        //.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

 
  
  
 

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 中添加如下代码,测试对应的DebugInformationWarningError方法

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进行配置

看完上述内容,你们掌握如何在Asp.Net MVC中对Serilog进行配置的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网站标题:如何在Asp.NetMVC中对Serilog进行配置-创新互联
文章转载:http://cdkjz.cn/article/didsge.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220