AspNetCore使用NLog做日志记录

  • A+
所属分类:.NET技术
摘要

安装nuget包NLog.Web.AspNetCore和Microsoft.Extensions.Logging


安装包

安装nuget包NLog.Web.AspNetCoreMicrosoft.Extensions.Logging

配置文件NLog.config

AspNetCore使用NLog做日志记录

<?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"       xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"       autoReload="true"       throwExceptions="false"       internalLogLevel="Off" internalLogFile="c:tempnlog-internal.log"> 	<variable name="myvar" value="myvalue" /> 	<extensions> 		<add assembly="NLog.Web.AspNetCore" /> 	</extensions> 	<targets> 		<!--Error保存至文件--> 		<target name="error_file" xsi:type="File" maxArchiveFiles="30"  encoding="utf-8"             fileName="${basedir}/Logs/${date:yyyyMMdd}_Error.log"             archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_Error.{#}.log"             archiveDateFormat="yyyyMMdd"             archiveAboveSize="104857600"             archiveNumbering="Sequence"             layout="${date:yyyy-MM-dd HH:mm:ss} ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace}" /> 		<!--Trace保存至文件--> 		<target name="trace_file" xsi:type="File" maxArchiveFiles="30" encoding="utf-8"             fileName="${basedir}/Logs/${date:yyyyMMdd}_Trace.log"             archiveFileName="${basedir}/Logs/${date:yyyyMMdd}_Trace.{#}.log"             archiveDateFormat="yyyyMMdd"             archiveAboveSize="104857600"             archiveNumbering="Sequence"             layout="${date:yyyy-MM-dd HH:mm:ss} ${uppercase:${level}}: ${message}" /> 	</targets>  	<rules> 		<logger name="*" minlevel="Info" maxlevel="Warn" writeTo="trace_file" /> 		<logger name="*" minlevel="Error" writeTo="error_file" /> 	</rules> </nlog> 

Program修改

AspNetCore使用NLog做日志记录

正常的依赖注入使用日志

AspNetCore使用NLog做日志记录