在Asp.Net MVC 中配置 Serilog

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

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

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

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

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

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

  

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

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

时间: 2024-08-05 19:27:42

在Asp.Net MVC 中配置 Serilog的相关文章

asp.net mvc中配置路由默认值(Area中)

public class RouteConfig { private static string[] namespaces = new string[1] { "Best.Site.Areas.BestPalace" }; public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Ignore

log4net 使用总结- (2)在ASP.NET MVC 中使用

log4net在ASP.NET MVC中的配置,还有一种配置方式,即不在web.config中,而是单独新建一个log4net.config 在根目录下 第一.引用log4net.dll 第二.在站点根目录下增加log4net.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="

ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器

ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器一:闲谈一下:1.现在任务跟踪管理系统已经开发快要结束了,抽一点时间来写一下,想一想自己就有成就感啊!!  2.关于任务跟踪管理系统项目中遇到的Windows服务以及Webservice的综合应用的问题. 大家好这是我第二次写博客 ,写的不好请大家多多谅解, 希望大家可以多多指正. 二:我稍微的整理了一下关于这个分布式定时器需求:1.根据任务跟踪管理系统中的数据库的AnswerSheet 表格中找到客户编

KindEditor上传本地图片在ASP.NET MVC的配置

http://www.cnblogs.com/upupto/archive/2010/08/24/1807202.html 本文解决KindEditor上传本地图片在ASP.NET MVC中的配置. 开发工具:VS 2010 EN 开发语言:Visual C# ASP.NET MVC 2.0 kindeditor-3.5-zh_CN 下载 文中以Blog文章为例,为做演示,数据表比较简单,如下图: 添加 BlogController Code: 1 2 3 4 5 6 7 8 9 10 11 1

Asp.Net MVC中使用ACE模板之Jqgrid

第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究.它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间. 发现虽然不是完美,整体效果还是不错,特此分享给园友.这一节先讲其中的Jqgrid.按照国际惯例,先上两张图. 集成了button,form,treeview以及日历,时间轴.chart等控件,非常丰富.下面是Jqgrid在MVC中的使用. jqgrid的加载,排序,查找都是基于后台方法,不是在内存中完成,但也有一些小坑.下面一一道

Ioc容器Autofac系列(2)-- asp.net mvc中整合autofac(转)

经过上篇蜻蜓点水的介绍后,本篇通过实例快速上手autofac,展示当asp.net mvc引入了autofac之后会带来什么. 创建Asp.net MVC并引入Autofac 首先,创建一个MVC站点,为方便起见,选初始带HomeController和AccountController的那种.然后通过NuGet或到Autofac官网下载来引入类库.个人推荐前者,因为从VS2010开始,已内集可视化的NuGet功能,使用起来非常方便.如下图所示: 这是vs2012的界面,点击"Manage NuG

ASP.NET MVC 中的路由

普通的路由 在以前版本的ASP.NET MVC里,这些规则会被定义在RouteConfig.cs文件,也有Routing Assistant扩展可以实现基于特性的路由,不过是收费滴,另外还有一个扩展:http://attributerouting.net/ ,也很不错:理论上ASP.NET MVC 中要实现任意的规则URL 应该是没有问题的. 比如配置的酒店详情页路由 //HOTEL DETAIL routes.MapRoute(name: "HotelDetail", url: &q

log4net 使用总结- (1)在ASP.NET MVC 中使用

1. 去官网下载log4net.dll,增加引用到站点下(你也可以通过nuget 安装) http://logging.apache.org/log4net/download_log4net.cgi 2. 在Web.config中增加配置(这里按日志文件输出) <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, lo

Asp.NET MVC 中使用 SignalR 实现推送功能

一,简介 Signal 是微软支持的一个运行在 Dot NET 平台上的 html websocket 框架.它出现的主要目的是实现服务器主动推送(Push)消息到客户端页面,这样客户端就不必重新发送请求或使用轮询技术来获取消息. 可访问其官方网站:https://github.com/SignalR/ 获取更多资讯. 二.Asp.net SignalR 是个什么东东 Asp.net SignalR是微软为实现实时通信的一个类库.一般情况下,SignalR会使用JavaScript的长轮询(lo