您的位置:首页 > 编程语言 > ASP

[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"

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代码,大家还是自己敲吧,因为偷懒的木匠从来都不是好司机。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: