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

Asp.Net Core 2.0 之旅---NLog日志的使用教程

2018-01-17 13:14 1146 查看
1、安装NLog,搜索 NLog.Web.AspNetCore,并将它安装在web项目中。

2、配置NLog,在StartUpzz启动类中的 Configure 方法中 配置NLog



3、 配置nlog.config文件,首先在项目根目录下新建文件nlog.config,将下面的信息复制到此文件中。配置文件中的targets节点是我们重要关注点:

type="File" 表示 输出为文件类型,

fileName="${basedir}/Logs/${shortdate}/nlog-all-${shortdate}.log" 表示 文件的路径(${dasedir}这个指定用于获取网站的根路径,不知道为啥项目调试时,总是无缘无故停止,把${basedir}/Logs/去掉就正常,这个记录一下,也希望有遇到的朋友能够帮忙解决。当前配置的文件路径如果发布到 Linux上的话,可能不会生成日志文件,这可能是Linux的文件权限的问题,需要赋予项目所在的文件夹rw的权限。)

layout="${longdate}|${logger}|${uppercase:${level}}|  ${message} ${exception}"  表示 日志输出的样式,这里我不做过多的解释,因为这方面的资料很全,大家可以自行搜索。

<?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"
internalLogLevel="info"
internalLogFile="NLogInternal.log">

<!-- Load the ASP.NET Core plugin -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>

<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="${basedir}/Logs/${shortdate}/nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" />

<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="${basedir}/Logs/${shortdate}/nlog-own-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" />

<!-- write to the void aka just remove -->
<target xsi:type="Null" name="blackhole" />
</targets>

<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />

<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>4、配置完成后,我们就可以愉快的使用这个NLogL了。



上面的例子 是使用 构造方法依赖注入的方式,如果不了解依赖注入的话,请看我的系列教程 Asp.Net Core 2.0 之旅---AutoFac IOC容器的使用教程

5、至此就可以使用它了。

_logger.LogInformation("1");
_logger.LogWarning("1");
_logger.LogDebug("1");是不是 很简单呢? 
备注:如果有跟我一样喜欢 NET CORE 的,请加599063383这个群。让我们共同进步!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐