Return to Snippet

Revision: 21324
at September 29, 2010 08:42 by pckujawa


Updated Code
[app.config]
<?xml version="1.0"?>
<configuration>
    <configSections>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<variable name="appTitle" value="My Application"/>
		<variable name="logFilePath" value="${specialfolder:folder=Desktop:file=${appTitle} log.log}"/>

		<targets async="true">
			<target name="file" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message}${newline}(${stacktrace}) ${exception:format=ToString}"/>
			
			<target name="fileAsInfo" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message} ${exception:format=ToString}"/>
			
			<target xsi:type="EventLog" name="eventLog" source="${appTitle}" layout="${message}${newline}${exception:format=tostring}"/>
		</targets>
		
		<targets>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. Please see the log file (${logFilePath}) or event log for more details."/>
		</targets>

		<rules>
			<logger name="*" level="Info" writeTo="fileAsInfo"/>
			<logger name="*" minlevel="Warn" writeTo="file"/>
			<logger name="*" minlevel="Warn" writeTo="eventLog"/>
			<logger name="*" minlevel="Error" writeTo="mbox"/>
		</rules>
	</nlog>
</configuration>

// WinForms App
static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        string message = String.Format(
            "(Application version {0}) {1}", Application.ProductVersion, exc.Message);

        _logger.FatalException(message, exc);
        Application.Exit(); // Encouraged, but not required
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
            if (e.IsTerminating)
            {
                _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
            }
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

// WPF App
// App.xaml:
<Application x:Class="UI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DispatcherUnhandledException="Application_DispatcherUnhandledException"
    Startup="Application_Startup"
    StartupUri="UserInterface.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

// App.xaml.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private readonly Logger _logger = LogManager.GetLogger("App");

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // UI Exceptions
        this.DispatcherUnhandledException += Application_DispatcherUnhandledException;

        // Thread exceptions
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        var exception = e.Exception;
        HandleUnhandledException(exception);
    }
    
    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    {
        HandleUnhandledException(unhandledExceptionEventArgs.ExceptionObject as Exception);
        if (unhandledExceptionEventArgs.IsTerminating)
        {
            _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
        }
    }

    private void HandleUnhandledException(Exception exception)
    {
        string message = "Unhandled exception";
        try
        {
            AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception exc)
        {
            _logger.ErrorException("Exception in unhandled exception handler", exc);
        }
        finally
        {
            _logger.ErrorException(message, exception);
        }
    }
}

Revision: 21323
at September 29, 2010 08:32 by pckujawa


Updated Code
[app.config]
<?xml version="1.0"?>
<configuration>
    <configSections>
        </sectionGroup>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<variable name="appTitle" value="My Application"/>
		<variable name="logFilePath" value="${specialfolder:folder=Desktop:file=${appTitle} log.log}"/>

		<targets async="true">
			<target name="file" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message}${newline}(${stacktrace}) ${exception:format=ToString}"/>
			
			<target name="fileAsInfo" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message} ${exception:format=ToString}"/>
			
			<target xsi:type="EventLog" name="eventLog" source="${appTitle}" layout="${message}${newline}${exception:format=tostring}"/>
		</targets>
		
		<targets>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. Please see the log file (${logFilePath}) or event log for more details."/>
		</targets>

		<rules>
			<logger name="*" level="Info" writeTo="fileAsInfo"/>
			<logger name="*" minlevel="Warn" writeTo="file"/>
			<logger name="*" minlevel="Warn" writeTo="eventLog"/>
			<logger name="*" minlevel="Error" writeTo="mbox"/>
		</rules>
	</nlog>
</configuration>

// WinForms App
static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        string message = String.Format(
            "(Application version {0}) {1}", Application.ProductVersion, exc.Message);

        _logger.FatalException(message, exc);
        Application.Exit(); // Encouraged, but not required
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
            if (e.IsTerminating)
            {
                _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
            }
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

// WPF App
// App.xaml:
<Application x:Class="UI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DispatcherUnhandledException="Application_DispatcherUnhandledException"
    Startup="Application_Startup"
    StartupUri="UserInterface.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

// App.xaml.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private readonly Logger _logger = LogManager.GetLogger("App");

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // UI Exceptions
        this.DispatcherUnhandledException += Application_DispatcherUnhandledException;

        // Thread exceptions
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        var exception = e.Exception;
        HandleUnhandledException(exception);
    }
    
    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    {
        HandleUnhandledException(unhandledExceptionEventArgs.ExceptionObject as Exception);
        if (unhandledExceptionEventArgs.IsTerminating)
        {
            _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
        }
    }

    private void HandleUnhandledException(Exception exception)
    {
        string message = "Unhandled exception";
        try
        {
            AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception exc)
        {
            _logger.ErrorException("Exception in unhandled exception handler", exc);
        }
        finally
        {
            _logger.ErrorException(message, exception);
        }
    }
}

Revision: 21322
at July 24, 2010 01:26 by pckujawa


Updated Code
[app.config]
<?xml version="1.0"?>
<configuration>
    <configSections>
        </sectionGroup>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<variable name="appTitle" value="My Application"/>
		<variable name="logFilePath" value="${specialfolder:folder=Desktop:file=${appTitle} log.log}"/>

		<targets async="true">
			<target name="file" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message}${newline}(${stacktrace}) ${exception:format=ToString}"/>
			
			<target name="fileAsInfo" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message} ${exception:format=ToString}"/>
			
			<target xsi:type="EventLog" name="eventLog" source="${appTitle}" layout="${message}${newline}${exception:format=tostring}"/>
		</targets>
		
		<targets>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. Please see the log file (${logFilePath}) or event log for more details."/>
		</targets>

		<rules>
			<logger name="*" level="Info" writeTo="fileAsInfo"/>
			<logger name="*" minlevel="Warn" writeTo="file"/>
			<logger name="*" minlevel="Warn" writeTo="eventLog"/>
			<logger name="*" minlevel="Error" writeTo="mbox"/>
		</rules>
	</nlog>
</configuration>

// WinForms App
static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        string message = String.Format(
            "(Application version {0}) {1}", Application.ProductVersion, exc.Message);

        _logger.FatalException(message, exc);
        Application.Exit(); // Encouraged, but not required
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
            if (e.IsTerminating)
            {
                _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
            }
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

// WPF App
// App.xaml:
<Application x:Class="UI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DispatcherUnhandledException="Application_DispatcherUnhandledException"
    StartupUri="UserInterface.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

// App.xaml.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private readonly Logger _logger = LogManager.GetLogger("App");

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // UI Exceptions
        this.DispatcherUnhandledException += Application_DispatcherUnhandledException;

        // Thread exceptions
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        var exception = e.Exception;
        HandleUnhandledException(exception);
    }
    
    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    {
        HandleUnhandledException(unhandledExceptionEventArgs.ExceptionObject as Exception);
        if (unhandledExceptionEventArgs.IsTerminating)
        {
            _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
        }
    }

    private void HandleUnhandledException(Exception exception)
    {
        string message = "Unhandled exception";
        try
        {
            AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception exc)
        {
            _logger.ErrorException("Exception in unhandled exception handler", exc);
        }
        finally
        {
            _logger.ErrorException(message, exception);
        }
    }
}

Revision: 21321
at July 15, 2010 02:25 by pckujawa


Updated Code
[app.config]
<?xml version="1.0"?>
<configuration>
    <configSections>
        </sectionGroup>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<variable name="appTitle" value="My Application"/>
		<variable name="logFilePath" value="${specialfolder:folder=Desktop:file=${appTitle} log.log}"/>

		<targets async="true">
			<target name="file" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message}${newline}(${stacktrace}) ${exception:format=ToString}"/>
			
			<target name="fileAsInfo" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message} ${exception:format=ToString}"/>
			
			<target xsi:type="EventLog" name="eventLog" source="${appTitle}" layout="${message}${newline}${exception:format=tostring}"/>
		</targets>
		
		<targets>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. Please see the log file (${logFilePath}) or event log for more details."/>
		</targets>

		<rules>
			<logger name="*" level="Info" writeTo="fileAsInfo"/>
			<logger name="*" minlevel="Warn" writeTo="file"/>
			<logger name="*" minlevel="Warn" writeTo="eventLog"/>
			<logger name="*" minlevel="Error" writeTo="mbox"/>
		</rules>
	</nlog>
</configuration>

// WinForms App
static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        string message = String.Format(
            "(Application version {0}) {1}", Application.ProductVersion, exc.Message);

        _logger.FatalException(message, exc);
        Application.Exit(); // Encouraged, but not required
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

// WPF App
// App.xaml:
<Application x:Class="UI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DispatcherUnhandledException="Application_DispatcherUnhandledException"
    StartupUri="UserInterface.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

// App.xaml.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private readonly Logger _logger = LogManager.GetLogger("App");

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // UI Exceptions
        this.DispatcherUnhandledException += Application_DispatcherUnhandledException;

        // Thread exceptions
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        var exception = e.Exception;
        HandleUnhandledException(exception);
    }
    
    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    {
        HandleUnhandledException(unhandledExceptionEventArgs.ExceptionObject as Exception);
        if (unhandledExceptionEventArgs.IsTerminating)
        {
            _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
        }
    }

    private void HandleUnhandledException(Exception exception)
    {
        string message = "Unhandled exception";
        try
        {
            AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception exc)
        {
            _logger.ErrorException("Exception in unhandled exception handler", exc);
        }
        finally
        {
            _logger.ErrorException(message, exception);
        }
    }
}

Revision: 21320
at July 13, 2010 03:10 by pckujawa


Updated Code
[app.config]
<?xml version="1.0"?>
<configuration>
    <configSections>
        </sectionGroup>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<variable name="appTitle" value="My Application"/>
		<variable name="logFilePath" value="${specialfolder:folder=Desktop:file=${appTitle} log.log}"/>

		<targets async="true">
			<target name="file" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message}${newline}(${stacktrace}) ${exception:format=ToString}"/>
			
			<target name="fileAsInfo" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message} ${exception:format=ToString}"/>
			
			<target xsi:type="EventLog" name="eventLog" source="${appTitle}" layout="${message}${newline}${exception:format=tostring}"/>
		</targets>
		
		<targets>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. Please see the log file (${logFilePath}) or event log for more details."/>
		</targets>

		<rules>
			<logger name="*" level="Info" writeTo="fileAsInfo"/>
			<logger name="*" minlevel="Warn" writeTo="file"/>
			<logger name="*" minlevel="Warn" writeTo="eventLog"/>
			<logger name="*" minlevel="Error" writeTo="mbox"/>
		</rules>
	</nlog>
</configuration>


static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        string message = String.Format(
            "(Application version {0}) {1}", Application.ProductVersion, exc.Message);

        _logger.FatalException(message, exc);
        Application.Exit(); // Encouraged, but not required
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

Revision: 21319
at February 19, 2010 15:36 by pckujawa


Updated Code
[app.config]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	
		<targets>
			<target name="file" xsi:type="File" fileName="${specialfolder:folder=Desktop}/MyApp log.log"
	 layout="${longdate} ${level:upperCase=true}: ${message}${newline}${stacktrace} ${exception:format=ToString}"/>
			<target xsi:type="EventLog" name="eventLog" source="MyApp" layout="${stacktrace}${newline}${message}${newline}${exception:format=tostring}"/>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="${message}${newline}${stacktrace}${newline}${exception:format=ToString}" />
			<!--<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. If necessary, please contact Someone at [email protected]. (You can click on this window and press Ctrl+C to copy this text.)${newline}${newline}${message}" />-->		</targets>
	
		<rules>
			<logger name="*" minlevel="Debug" writeTo="file" />
			<logger name="*" minlevel="Debug" writeTo="eventLog" />
			<logger name="*" minlevel="Error" writeTo="mbox" />
		</rules>
	</nlog>	
</configuration>


static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        _logger.FatalException(string.Empty, exc); 
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

Revision: 21318
at January 11, 2010 17:02 by pckujawa


Updated Code
[app.config]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	
		<targets>
			<target name="file" xsi:type="File" fileName="${specialfolder:folder=Desktop}/MyApp log.log"
	 layout="${longdate} ${level:upperCase=true}: ${message}${newline}${stacktrace} ${exception:format=ToString}"/>
			<target xsi:type="EventLog" name="eventLog" source="MyApp" layout="${stacktrace}${newline}${message}${newline}${exception:format=tostring}"/>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="${message}${newline}${stacktrace}${newline}${exception:format=ToString}" />
			<!--<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. If necessary, please contact Someone at [email protected]. (You can click on this window and press Ctrl+C to copy this text.)${newline}${newline}${message}" />-->		</targets>
	
		<rules>
			<logger name="*" minlevel="Debug" writeTo="file" />
			<logger name="*" minlevel="Debug" writeTo="eventLog" />
			<logger name="*" minlevel="Error" writeTo="mbox" />
		</rules>
	</nlog>	
</configuration>


static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
        }
    }

    private static void LogFatalException(Exception exc)
    {
        _logger.FatalException(string.Empty, exc); 
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

Revision: 21317
at January 11, 2010 16:58 by pckujawa


Updated Code
[app.config]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	
		<targets>
			<target name="file" xsi:type="File" fileName="${specialfolder:folder=Desktop}/MyApp log.log"
	 layout="${longdate} ${level:upperCase=true}: ${message}${newline}${stacktrace} ${exception:format=ToString}"/>
			<target xsi:type="EventLog" name="eventLog" source="MyApp" layout="${stacktrace}${newline}${message}${newline}${exception:format=tostring}"/>
			<!--Debugging: "${message}${newline}${stacktrace}${newline}${exception:format=ToString}"-->
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. If necessary, please contact Someone at [email protected]. (You can click on this window and press Ctrl+C to copy this text.)${newline}${newline}${message}" />
		</targets>
	
		<rules>
			<logger name="*" minlevel="Debug" writeTo="file" />
			<logger name="*" minlevel="Debug" writeTo="eventLog" />
			<logger name="*" minlevel="Error" writeTo="mbox" />
		</rules>
	</nlog>	
</configuration>


static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
        }
    }

    private static void LogFatalException(Exception exc)
    {
#if DEBUG
        _logger.FatalException(exc.ToString(), exc); 
#else
        _logger.FatalException(string.Empty, exc); 
#endif
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

Revision: 21316
at December 10, 2009 12:33 by pckujawa


Initial Code
[app.config]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
			<section name="HawkConfigGUI.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
		</sectionGroup>

		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	
		<targets>
			<target name="file" xsi:type="File" fileName="${specialfolder:folder=Desktop}/MyApp log.log"
	 layout="${longdate} ${level:upperCase=true}: ${message}${newline}${stacktrace} ${exception:format=ToString}"/>
			<target xsi:type="EventLog" name="eventLog" source="MyApp" layout="${stacktrace}${newline}${message}${newline}${exception:format=tostring}"/>
			<!--Debugging: "${message}${newline}${stacktrace}${newline}${exception:format=ToString}"-->
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. If necessary, please contact Someone at [email protected]. (You can click on this window and press Ctrl+C to copy this text.)${newline}${newline}${message}" />
		</targets>
	
		<rules>
			<logger name="*" minlevel="Debug" writeTo="file" />
			<logger name="*" minlevel="Debug" writeTo="eventLog" />
			<logger name="*" minlevel="Error" writeTo="mbox" />
		</rules>
	</nlog>
	
	<userSettings>
		<HawkConfigGUI.Properties.Settings>
   <setting name="FpgaFilePath" serializeAs="String">
    <value />
   </setting>
  </HawkConfigGUI.Properties.Settings>
	</userSettings>
</configuration>


static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
        }
    }

    private static void LogFatalException(Exception exc)
    {
#if DEBUG
        _logger.FatalException(exc.ToString(), exc); 
#else
        _logger.FatalException(string.Empty, exc); 
#endif
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }

    private static Logger _logger = LogManager.GetCurrentClassLogger();
}

Initial URL
http://nlog-project.org

Initial Description
[NLog](http://nlog-project.org) is an awesome, simple logging solution for .NET. In the code below, there is an example entry into app.config (there are other methods for doing NLog config files, but I have found that this one works with ClickOnce deployments). There is also a snippet for catching and logging all exceptions in a WinForms application and one for a WPF application.

I also have a [question on stackoverflow](http://stackoverflow.com/questions/4091606/most-useful-nlog-configurations) with a lot of useful NLog configuration answers.

Initial Title
Logging in .NET with NLog (default config file, catch all exceptions and route to logger, ...)

Initial Tags


Initial Language
C#