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

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

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

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

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

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       autoReload="true">
 5 
 6   <targets>
 7     <target name="logfile"
 8             xsi:type="File"
 9             fileName="c://logs/${shortdate}.log"
10             layout="${longdate}|${level:uppercase=true}|${logger}|${event-context:item=EventId}|${message}|${ndc}" />
11     <target name="console"
12             xsi:type="ColoredConsole"
13             layout="[${level:uppercase=true}:${logger}] ${message}"/>
14   </targets>
15 
16   <rules>
17     <logger name="*" minlevel="Info" writeTo="logfile,console" />
18   </rules>
19 </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.然后就同时在控制台和日志文件中记录日志(因为配置文件中配置了两种日志记录方式):

原文地址:https://www.cnblogs.com/aspnet5/p/4846923.html