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 > )
{
var titleAttribute = (AssemblyTitleAttribute)attributes[];
if (titleAttribute.Title.Length > )
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

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

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

    public class RouteConfig { ] { "Best.Site.Areas.BestPalace" }; public static void Register ...

  2. 在ASP.Net MVC 中,如何在Global.asax中配置一个指向Area内部的默认Route

    ASP.Net MVC 中配置Route的时候可以设置一个默认的Route. 比如我要在输入http://localhost的时候默认进入http://localhost/home/index.可以在 ...

  3. ASP.NET MVC 学习笔记-7.自定义配置信息 ASP.NET MVC 学习笔记-6.异步控制器 ASP.NET MVC 学习笔记-5.Controller与View的数据传递 ASP.NET MVC 学习笔记-4.ASP.NET MVC中Ajax的应用 ASP.NET MVC 学习笔记-3.面向对象设计原则

    ASP.NET MVC 学习笔记-7.自定义配置信息   ASP.NET程序中的web.config文件中,在appSettings这个配置节中能够保存一些配置,比如, 1 <appSettin ...

  4. 如何在 ASP.NET MVC 中集成 AngularJS(2)

    在如何在 ASP.NET MVC 中集成 AngularJS(1)中,我们介绍了 ASP.NET MVC 捆绑和压缩.应用程序版本自动刷新和工程构建等内容. 下面介绍如何在 ASP.NET MVC 中 ...

  5. 在 ASP.NET MVC 中充分利用 WebGrid (microsoft 官方示例)

    在 ASP.NET MVC 中充分利用 WebGrid https://msdn.microsoft.com/zh-cn/magazine/hh288075.aspx Stuart Leeks 下载代 ...

  6. ASP.NET MVC中的错误处理

    ASP.NET MVC中的错误的错误处理跨越了两个主要领域:程序异常和路由异常的处理.前者是关于在控制器和视图中捕获错误的;而后者更多是有关重定向和HTTP错误的. 1.在WebConfig中把过滤器 ...

  7. 如何在 ASP.NET MVC 中集成 AngularJS(1)

    介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 REST 的 Web API 服务.另外,还有最新的数据库技术.最新 ...

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

    ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器一:闲谈一下:1.现在任务跟踪管理系统已经开发快要结束了,抽一点时间来写一下,想一想自己就有成就感啊!!  ...

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

    http://www.cnblogs.com/upupto/archive/2010/08/24/1807202.html 本文解决KindEditor上传本地图片在ASP.NET MVC中的配置. ...

随机推荐

  1. Salesforce ADM201备考心得

    Salesforce拥有很多针对不同角色的认证考试.ADM201是面对初级管理员的认证. 考试形式是单选题和多选题(如果是多选题,题干上会提示你要多选),两个小时时间,60道题目.内容涉及管理Sale ...

  2. UV动画

    [猫猫的Unity Shader之旅]之纹理映射 http://blog.csdn.net/dbtxdxy/article/details/46954417 [猫猫的Unity Shader之旅]之U ...

  3. linux大文件分割 split命令

    inux split 命令 功能说明:切割文件. 语 法:split [--help][--version][-][-b ][-C ][-l ][要切割的文件][输出文件名] 补充说明:split可将 ...

  4. Springsecurity3.1.3配置多个登陆页面

    需求:网站的前台和后台不同的url需要不同的登陆页面,不同的异常捕获方式. spring-security3.1以后的版本支持多个<http>标签,因此本文所采用的方式就是使用两个,实际上 ...

  5. mysqldump数据库同步遇到的问题

    1.同步数据是遇到 没有 lock database权限,报 " mysqldump: Got error: 1044: Access denied for user 'spider_dat ...

  6. Thrift的TBinaryProtocol二进制协议分析

    先上张图,说明一下thrift的二进制协议是什么东东. 报文格式编码: bool类型: 一个字节的类型,两个字节的字段编号,一个字节的值(true:1,false:0). Byte类型: 一个字节的类 ...

  7. C++程序设计基础

    01 1 预编译常用的有,宏定义和包含库.2 库:是实用工具的集和,由程序员编写,可以完成一些特定的功能.3 <> 系统库 ""用户自定义库.4 宏定义:定义符号常量, ...

  8. sql 取新的列名含义

    SELECT a.*, 1 DELETABLE, '' YEAR_ON, '' MONTH_ON, TOOL_STATUS status0 FROM TOOL a 说明:其中tool字段有tool_s ...

  9. PHP获取某月天数

    方式一: <?php function days($year,$month){ if($month<10){ $month = '0'.$month; } if($month == 12) ...

  10. C#数字日期装换为中文日期

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...