<ItemGroup> <PackageReference Include="NLog" Version="4.7.13" /> <PackageReference Include="NLog.Config" Version="4.7.13" /> <PackageReference Include="NLog.Schema" Version="4.7.13" /> </ItemGroup>
正常来说, 安装了 NLog.Config
, 另外两个也会自动安装, 如果没有, 则手动安装
需要NLog.xsd
与NLog.config
文件
上一步操作完成后, 有可能可以看到这两个文件, 但是不能编辑, 可以打开所在路径, 然后复制到项目中, 重新添加
如果上一步操作完成后没有在项目中看到, 则可以从如下路径拿到默认的文件:
NLog.config: C:\Users\laolang\.nuget\packages\nlog.config\4.7.13\contentFiles\any\any NLog.xsd: C:\Users\laolang\.nuget\packages\nlog.schema\4.7.13\contentFiles\any\any
复制到当前项目, 修改NLog.config
的属性为始终复制, 然后修改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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"> <targets> <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${logger}:${callsite-linenumber} - ${message}" /> <target name="logConsole" xsi:type="Console" layout="${longdate} ${uppercase:${level}} ${logger}:${callsite-linenumber} - ${message}"/> </targets> <rules> <logger name="*" minlevel="Info" writeTo="f"/> <logger name="*" minlevel="Debug" writeTo="logConsole"/> </rules> </nlog>
using System.Windows; namespace my_tools { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { // 引入 Logger private static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { // 打印日志 log.Info("hello world"); } } }
效果如下
2022-02-03 23:55:14.3568 INFO my_tools.MainWindow:19 - hello world
WPF .NET 5.0 控制台没有输出