[walkthrough] 在Asp.net MVC6 RC里使用NLog,并且把配置集成到config.json
2015-06-17 09:33
591 查看
说明一下:本文基于随visual studio 2015 RC公开的DNX1.0.0-beta4,git上最新的aspnet的开发版本已经发生了很大变化。
首先,理论部分看[汤姆大叔的博客] 解读ASP.NET 5 & MVC6系列(9):日志框架
实际上aspnet的开发人员已经在最近版的系统里开始集成nlog了。 本文的目的主要帮助大家理解aspnet mvc 6的框架。
新建工程 "NlogTest"
View Code
实例化Nlog.LogFactory类,并从config里读取的配置,设置到该LogFactory里。
下面是NLog的使用了。
◎打开 Startup.cs文件,并在Configure函数里AddLog。
◎在Controller里使用
打开HomeController.cs文件,并追加代码。
编译通过后,F5一下,看看自己的成果吧。
本文完结。
另外,俺不会提供完整的project代码,大家还是自己敲吧,因为偷懒的木匠从来都不是好司机。
首先,理论部分看[汤姆大叔的博客] 解读ASP.NET 5 & MVC6系列(9):日志框架
实际上aspnet的开发人员已经在最近版的系统里开始集成nlog了。 本文的目的主要帮助大家理解aspnet mvc 6的框架。
新建工程 "NlogTest"
using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.Logging; using System; using System.Linq; using System.Text; namespace NLogTest { public static class NLogLoggerFactoryExtensions { public static ILoggerFactory AddNLog( this ILoggerFactory factory, IConfiguration configuration) { var config = new global::NLog.Config.LoggingConfiguration(); var targets = configuration.GetSubKey("targets"); foreach (var item in targets.GetSubKeys()) { AddTargets(config, item.Key, item.Value); } var rules = configuration.GetSubKey("rules"); foreach (var item in rules.GetSubKeys()) { AddLoggingRule(config, item.Value); } factory.AddProvider(new NLogProvider(new global::NLog.LogFactory(config))); return factory; } private static void AddTargets(global::NLog.Config.LoggingConfiguration configuration, string targetName, IConfiguration targetConf) { string targetType = ""; if (targetConf.TryGet("type", out targetType)) { switch (targetType.ToLower()) { case "file": configuration.AddTarget(targetName, GenFileTarget(targetName, targetConf)); break; case "mail": configuration.AddTarget(targetName, GenMailTarget(targetName, targetConf)); break; default: break; } } } private static global::NLog.Targets.Target GenFileTarget(string targetName, IConfiguration targetConf) { var fileTarget = new global::NLog.Targets.FileTarget(); fileTarget.Name = targetName; string confVal = GetVal(targetConf, "fileName"); if (string.IsNullOrEmpty(confVal)) { //Filename is not setting , throw exception! throw new ArgumentNullException("fileTarget's filename is empty."); } fileTarget.FileName = confVal; confVal = GetVal(targetConf, "layout"); if (!string.IsNullOrEmpty(confVal)) { fileTarget.Layout = confVal; } confVal = GetVal(targetConf, "keepfileopen"); if (!string.IsNullOrEmpty(confVal)) { fileTarget.KeepFileOpen = (confVal.ToLower() == "true"); } confVal = GetVal(targetConf, "encoding"); if (!string.IsNullOrEmpty(confVal)) { fileTarget.Encoding = Encoding.GetEncoding(confVal); } fileTarget.AutoFlush = true; return fileTarget; } private static global::NLog.Targets.Target GenMailTarget(string targetName, IConfiguration targetConf) { var mailTarget = new global::NLog.Targets.MailTarget(); mailTarget.Name = targetName; string confVal = GetVal(targetConf, "to"); if (string.IsNullOrEmpty(confVal)) { //to is not setting , throw exception! throw new ArgumentNullException("mailTarget's [to] is empty."); } mailTarget.To = confVal; confVal = GetVal(targetConf, "from"); if (string.IsNullOrEmpty(confVal)) { //to is not setting , throw exception! throw new ArgumentNullException("mailTarget's [from] is empty."); } mailTarget.From = confVal; confVal = GetVal(targetConf, "layout"); if (!string.IsNullOrEmpty(confVal)) { mailTarget.Layout = confVal; } confVal = GetVal(targetConf, "subject"); if (!string.IsNullOrEmpty(confVal)) { mailTarget.Subject = confVal; } confVal = GetVal(targetConf, "smtpusername"); if (!string.IsNullOrEmpty(confVal)) { mailTarget.SmtpUserName = confVal; } confVal = GetVal(targetConf, "smtppassword"); if (!string.IsNullOrEmpty(confVal)) { mailTarget.SmtpPassword = confVal; } confVal = GetVal(targetConf, "smtpserver"); if (!string.IsNullOrEmpty(confVal)) { mailTarget.SmtpServer = confVal; } confVal = GetVal(targetConf, "smtpport"); if (!string.IsNullOrEmpty(confVal)) { int nPort = 25; if (int.TryParse(confVal, out nPort)) { mailTarget.SmtpPort = nPort; } } return mailTarget; } private static void AddLoggingRule(global::NLog.Config.LoggingConfiguration configuration, IConfiguration ruleConf) { string namePattern = "*"; string confVal = GetVal(ruleConf, " name"); if (!string.IsNullOrEmpty(confVal)) { namePattern = confVal; } confVal = GetVal(ruleConf, "minlevel"); global::NLog.LogLevel minLevel = global::NLog.LogLevel.Debug; if (!string.IsNullOrEmpty(confVal)) { minLevel = GetLogLevel(confVal, global::NLog.LogLevel.Trace); } confVal = GetVal(ruleConf, "writeto"); global::NLog.Targets.Target target = null; if (!string.IsNullOrEmpty(confVal)) { target = configuration.ConfiguredNamedTargets.Where(t => t.Name == confVal).FirstOrDefault(); } if (target != null) { configuration.LoggingRules.Add(new global::NLog.Config.LoggingRule(namePattern, minLevel, target)); } } private static string GetVal(IConfiguration configuration, string key) { string val = ""; if (configuration.TryGet(key, out val)) { return val; } else { return null; } } private static global::NLog.LogLevel GetLogLevel(string logLevel, global::NLog.LogLevel defaultLevel = null) { switch (logLevel.ToLower()) { case "debug": return global::NLog.LogLevel.Debug; case "info": return global::NLog.LogLevel.Info; case "warn": return global::NLog.LogLevel.Warn; case "error": return global::NLog.LogLevel.Error; case "fatal": return global::NLog.LogLevel.Fatal; } return defaultLevel; } } }
View Code
实例化Nlog.LogFactory类,并从config里读取的配置,设置到该LogFactory里。
下面是NLog的使用了。
◎打开 Startup.cs文件,并在Configure函数里AddLog。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) { // Configure the HTTP request pipeline. // Add the console logger. loggerfactory.AddConsole(); //Add the NLog logger loggerfactory.AddNLog(Configuration.GetSubKey("nlog")); //Log Output Test. var logger = loggerfactory.CreateLogger("NLogTest"); logger.LogInformation("this is infomation from startup"); try { var i = 100 - 100; var j = 100 / i; } catch (DivideByZeroException ex) { logger.LogError("error log test", ex); } 。。。。。。。。。。以下略 }
◎在Controller里使用
打开HomeController.cs文件,并追加代码。
public class HomeController : Controller { private ILogger _logger = null; public HomeController(ILoggerFactory logFactory) { _logger = logFactory.CreateLogger(nameof(HomeController)); _logger.LogWarning("I am created."); } public IActionResult Index() { _logger.LogWarning("hello from index of home control... "); return View(); } ・・・・・・・・・・・以下略 }
编译通过后,F5一下,看看自己的成果吧。
本文完结。
另外,俺不会提供完整的project代码,大家还是自己敲吧,因为偷懒的木匠从来都不是好司机。
相关文章推荐
- ASP.NET中使用Application对象实现简单在线人数统计功能
- ASP.NET中gridview获取当前行的索引值
- KindEditor编辑器在ASP.NET中的使用
- ASP.NET中使用Application对象实现简单在线人数统计功能
- 深入理解ASP.NET MVC Day1
- ASP.NET中绑定数据控件OnClientClick事件Eval函数解析错误的处理
- AspNetPager的使用
- ASP.NET MVC Web API 学习笔记---第一个Web API程序---近来很多大型的平台都公开了Web API
- ASP.NET中Web DataGrid的使用指南(转自前沿设计网-找到这个真不容易啊!)
- 未能加载文件或程序集“EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”或它的某一个
- 实例快速上手 -ASP.NET 4.5新特性WebAPI从入门到精通
- Asp.net 文本框全选的实现
- ASP.NET MVC搭建项目后台UI框架—8、将View中选择的数据行中的部分数据传入到Controller中
- NPOI与Aspose的导入导出保存
- asp.net mvc如何实现文件下载
- ASP.NET MVC学习笔记
- ASP.NET常见命名空间及其功能描述
- 如何设置ASP.NET页面的运行超时时间
- asp.net关于如何删除repeater里面的记录
- 浅谈ASP.NET中多层架构