在Asp.Net MVC 中配置 Serilog

 

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

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

 

1):下载而且安装Seq,具体的下载URL 为 【http://getseq.net/Download】,安装到默认的路径以后,实际上时候启动了一个Win Service,而且监听的端口号默认为 5341.api

安装的最后一步截图以下:app

 

而后咱们到Service列表中能够找到对应的Service, 以下图所示:测试

 

2):建立一个Asp.Net MVC 5的一个工程, 而后经过 Nuget 下载而且安装 对应的 package,以下图所示ui

  

 

3):在 App_Start 文件夹下建立一个 class 叫作 SerilogConfig.cs , 代码以下所示this

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 中添加补全所用到的 appSettingsspa

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

 

5):在 Startup.cs 中添加以下代码完成注册.net

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,Warning 和 Error 方法debug

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 记录, 以下截图

 

 

这样简单的配置 Serilog 就完成了, 同时咱们也能够到 C:\ProgramData\Seq\Logs 目录中找到 Log 的文本文件。

更多内容请看以下连接:

http://serilog.net/

https://github.com/serilog/serilog 

相关文章
相关标签/搜索