[英]How to use App.config in WPF application for log4net configuration
Currently im working on a WPF version of an existing console application. 目前我正在研究现有控制台应用程序的WPF版本。 In the console application i use log4net to do all my logging. 在控制台应用程序中,我使用log4net来完成所有日志记录。 Therefore i configured all my appenders etc in the App.config file. 因此我在App.config文件中配置了所有的appender等。 Everything works fine in the console application. 在控制台应用程序中一切正常。
Now i want to implement the same logging functionality in my WPF application. 现在我想在我的WPF应用程序中实现相同的日志记录功能。 I have to say that im totally new in WPF and this is my first WPF project. 我不得不说,我在WPF中是全新的,这是我的第一个WPF项目。 I just tried to add the App.config (exactly the same one) to my WPF project as i had it in my console application. 我只是尝试将App.config(完全相同的)添加到我的WPF项目中,就像我在控制台应用程序中一样。 But it does not work. 但它不起作用。 No files are created by the FileAppenders. FileAppenders不会创建任何文件。 But i also dont get any error or warning when compiling. 但是编译时我也没有收到任何错误或警告。
What do i have to do to get the same logging functionality for log4net as in my console app? 我需要做什么才能获得与我的控制台应用程序相同的log4net日志记录功能? How can i configure log4net (Appenders) in an WPF application? 如何在WPF应用程序中配置log4net(Appenders)?
Thx in advance Thx提前
xxxxxx Edit xxxxxx xxxxxx编辑xxxxxx
Based on Roberts hint i could solve it. 根据罗伯茨的提示,我可以解决它。 I added 我补充道
log4net.Config.XmlConfigurator.Configure()
to my Main Window. 到我的主窗口。 Now my logging works exactly in the same way as it does in my console application. 现在,我的日志记录与我的控制台应用程序中的日志记录完全相同。
public MainWindow()
{
// check if Application is already running
// if it is running - Kill
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Length > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
log4net.Config.XmlConfigurator.Configure();
InitializeComponent();
}
您需要在启动时调用log4net.Config.XmlConfigurator.Configure()
。
its simple, inside Window Constructor
just add this line like this 它的简单,在Window Constructor
只是像这样添加这一行
public MainWindow()
{
log4net.Config.XmlConfigurator.Configure();
InitializeComponent();
//.....
}
That's the way you do it a bit more in detail 这就是你更详细一点的方式
using System.Windows;
using log4net;
namespace Namespace
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override void OnStartup(StartupEventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
//Log.Info("Hello World");
base.OnStartup(e);
}
}
}
Don't forget to add log4net into the the configSections in your App.config 不要忘记将log4net添加到App.config中的configSections中
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.