nlog在.NET Core项目中使用案例
1、新建一个 .NET Core 项目,选择控制台应用程序,名称TestNetCore。
2、使用Nuget程序管理器,添加nlog,
3、添加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" throwExceptions="false" internalLogLevel="Warn" internalLogFile="logs/nlog.log"> <targets> <!--输出到数据库--> <target name="Database" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=localhost;database=mynetcore;user=root;password=123456;"> <commandText> insert into logs (date,level,message) values(@longdate,@level,@message); </commandText> <parameter name="@longdate" layout="${longdate}" /> <parameter name="@level" layout="${level}" /> <parameter name="@message" layout="${message}" /> </target> <target xsi:type="File" name="File" fileName="Logs/log.txt" layout="${longdate} | ${logger} | ${uppercase:${level}} | ${message} ${exception}" encoding="UTF-8"/> <!--输出到普通控制台--> <target name="Console" xsi:type="ColoredConsole" layout="${uppercase:${level}}:${longdate} | ${logger} | ${uppercase:${level}} | ${message} ${exception}"> </target> </targets> <rules> <!--跳过所有Info级别以下的Microsoft组件的日志记录--> <logger name="Microsoft.*" minlevel="Info" final="true" /> <!--注意这里的name="*",如果这里的name=xx了那么在C#的后台.cs文件使用日志的时候必须把xx当做参数来传递,否则没有日志输出--> <logger name="*" minlevel="Info" writeTo="Database" /> <logger name="*" minlevel="Trace" writeTo="Console" /> <logger name="*" minlevel="Debug" writeTo="File" /> </rules> </nlog>
注意:要把nlog.config属性设置成复制到输出目录
4、Program中添加如下
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Globalization; using System.Reflection; using log4net; using System.IO; using log4net.Repository; using log4net.Config; using NLog; namespace TestNetCore { internal class Program { static void Main(string[] args) { #region NLog Logger logger = NLog.LogManager.GetCurrentClassLogger(); logger.Fatal("Fatal"); logger.Error("Error"); logger.Warn("Warn"); logger.Info("Info"); logger.Debug("Debug"); logger.Trace("Trace"); #endregion Console.ReadLine(); } } }
5、运行效果
龙腾一族至尊龙骑