asp.net5中使用NLog进行日志记录

asp.net5中提供了性能强大的日志框架,本身也提供了几种日志记录方法,比如记录到控制台或者事件中等,但是,对大部分程序员来说,更喜欢使用类似log4net或者Nlog这种日志记录方式,灵活而强大。asp.net5中也包括NLog的实现,下面把最简单的使用方法写出来,抛砖引玉,让更多对此不熟悉的同学们能借此入门。

1.在project.json中添加对Microsoft.Framework.Logging.NLog的引用,目前最新是beta8版本:

asp.net5中使用NLog进行日志记录

2.然后添加NLog.config配置文件到项目根目录:

asp.net5中使用NLog进行日志记录

Nlog.config的内容可以参考如下:

 <?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"> <targets>
<target name="logfile"
xsi:type="File"
fileName="c://logs/${shortdate}.log"
layout="${longdate}|${level:uppercase=true}|${logger}|${event-context:item=EventId}|${message}|${ndc}" />
<target name="console"
xsi:type="ColoredConsole"
layout="[${level:uppercase=true}:${logger}] ${message}"/>
</targets> <rules>
<logger name="*" minlevel="Info" writeTo="logfile,console" />
</rules>
</nlog>

因为asp.net5启动目录不适合查看日志,所以这里直接把日志写死到固定文件夹内,没有使用相对目录。
3.取得nlog.config配置文件所在的目录,也就是系统根目录:

public Startup(IApplicationEnvironment env)
{
var builder = new ConfigurationBuilder(env.ApplicationBasePath)
.AddJsonFile("Config.json")
.AddEnvironmentVariables();
Configuration = builder.Build(); //取得系统启动目录
BasePath = env.ApplicationBasePath;
} //系统启动目录
public static string BasePath { get; set; }

这里把根目录存储到BasePath中。

4.根据配置文件生成Nlog日志对象

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
{
//nlog配置文件路径
string fileName = Path.Combine(BasePath, "nlog.config");
//nlog配置对象
NLog.Config.XmlLoggingConfiguration config = new NLog.Config.XmlLoggingConfiguration(fileName);
//添加Nlog到日志工厂
loggerfactory.AddNLog(new NLog.LogFactory(config)); var log = loggerfactory.CreateLogger("asp5test");
log.LogInformation("可以记录日志了!");

5.然后就同时在控制台和日志文件中记录日志(因为配置文件中配置了两种日志记录方式):

asp.net5中使用NLog进行日志记录

asp.net5中使用NLog进行日志记录

上一篇:微软日志工厂 Microsoft.Extensions.Logging 中增加 log4net 的日志输出


下一篇:漫游Kafka实现篇之分布式