Exception情報のログの残し方

C#のコーディング中にtry catchしているのですが、Exception情報をログに残す場合にどう残すのがよいか試した時のメモ。

候補として試してみた書き方は、以下の3種類

Exeption.Message

Exeption.StackTrace

Exeption.ToString()

実行結果は以下の通り。

***** ex.Message *****

意図的にException発生させました。


***** ex.StackTrace *****
‘ExceptionLog.exe’ (CoreCLR: clrhost): ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.6\System.Diagnostics.StackTrace.dll’ が読み込まれました。シンボルの読み込みをスキップしました。モジュールは最適化されていて、デバッグ オプションの [マイ コードのみ] 設定が有効になっています。
‘ExceptionLog.exe’ (CoreCLR: clrhost): ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.6\System.Reflection.Metadata.dll’ が読み込まれました。シンボルの読み込みをスキップしました。モジュールは最適化されていて、デバッグ オプションの [マイ コードのみ] 設定が有効になっています。
‘ExceptionLog.exe’ (CoreCLR: clrhost): ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.6\System.IO.FileSystem.dll’ が読み込まれました。シンボルの読み込みをスキップしました。モジュールは最適化されていて、デバッグ オプションの [マイ コードのみ] 設定が有効になっています。
‘ExceptionLog.exe’ (CoreCLR: clrhost): ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.6\System.Collections.Immutable.dll’ が読み込まれました。シンボルの読み込みをスキップしました。モジュールは最適化されていて、デバッグ オプションの [マイ コードのみ] 設定が有効になっています。
‘ExceptionLog.exe’ (CoreCLR: clrhost): ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.6\System.Text.Encoding.Extensions.dll’ が読み込まれました。シンボルの読み込みをスキップしました。モジュールは最適化されていて、デバッグ オプションの [マイ コードのみ] 設定が有効になっています。
at ExceptionLog.Form1.ThrowExceotion() in C:\Users\jono\Desktop\ブログ\02_Exception\ExceptionLog\ExceptionLog\Form1.cs:line 35

***** ex.ToString() *****
System.Exception: 意図的にException発生させました。
at ExceptionLog.Form1.ThrowExceotion() in C:\Users\jono\Desktop\ブログ\02_Exception\ExceptionLog\ExceptionLog\Form1.cs:line 35

今回の場合は、発生原因と発生場所が分かればよいのでException.ToString()が一番いい感じでしょうか。

利用したソースは以下です。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace ExceptionLog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Wrapper();
        }

        private void Wrapper()
        {
            ThrowExceotion();
        }

        private void ThrowExceotion()
        {
            try
            {
                throw new Exception("意図的にException発生させました。");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***** ex.Message *****");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine("***** ex.StackTrace *****");
                Debug.WriteLine(ex.StackTrace);
                Debug.WriteLine("***** ex.ToString() *****");
                Debug.WriteLine(ex.ToString());
            }
        }
    }
}

コメント

タイトルとURLをコピーしました