参考:https://blog.csdn.net/lordwish/article/details/103059254
输出日志到文件
使用NLog.Config。
首先去Nuget管理器搜索并安装NLog.Config(包含NLog,且容易编写配置文件)。装完有两个文件:
使用NLog.config进行配置:
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<!-- 输出至文件 -->
<target xsi:type="File" name="info_file" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}"/>
<target xsi:type="File" name="error_file" fileName="${basedir}/logs/${shortdate}_error.log"
layout="${longdate} ${uppercase:${level}} ${message} ${exception:stacktrace}" />
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Info" writeTo="info_file" />
<logger name="*" minlevel="Error" writeTo="error_file" />
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
在需要输出日志的时候只需要:
namespace TestAvalon
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private Logger logger = LogManager.GetCurrentClassLogger(); // 拿到
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
logger.Info("日志-start"); // 何时输出日志
}
}
}
那么点击绑定Button_Click的按钮,日志文件里就会输出:
输出日志到前台和文件
效果:
这里要安装 NLog.wpf.RichTextBox
当前已安装的NuGet包有:
装完会多几个文件,可以自行配置:
使用RichTextBox是为了写入带格式的文字。这个可以自己配置。
<RichTextBox x:Name="myctrl" Width="600" Height="100" Margin="100,10,100,10">
在初始化的时候这样配置:(我这里只是简单示例,所以放在MainWindow()中即可)
Dispatcher.Invoke(() =>
{
var target = new WpfRichTextBoxTarget
{
Name = "RichText",
Layout = "[${longdate:useUTC=false}] :: [${level:uppercase=true}] :: ${logger}:${callsite} :: ${message} ${exception:innerFormat=tostring:maxInnerExceptionLevel=10:separator=,:format=tostring}",
ControlName = "myctrl", // 写承载输出的控件名称
FormName = GetType().Name,
AutoScroll = true,
MaxLines = 1000,
UseDefaultRowColoringRules = true,
};
var asyncWrapper = new AsyncTargetWrapper { Name = "RichTextAsync", WrappedTarget = target };
LogManager.Configuration.AddTarget(asyncWrapper.Name, asyncWrapper);
LogManager.Configuration.LoggingRules.Insert(0, new LoggingRule("*", LogLevel.Info, asyncWrapper));
LogManager.ReconfigExistingLoggers();
});