Last active
August 29, 2015 14:01
-
-
Save KentaYamada/79479b23f86280e0a975 to your computer and use it in GitHub Desktop.
例外キャッチした時にログファイル出力する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
using System.IO; | |
using System.Text; | |
namespace LogFilerSample | |
{ | |
class Program | |
{ | |
private static readonly string _filePath = ConfigurationManager.AppSettings["LogFilePath"]; | |
private static readonly Encoding _encode = Encoding.GetEncoding("UTF-8"); | |
static void Main(string[] args) | |
{ | |
try | |
{ | |
Program.Func(); | |
} | |
catch (Exception ex) | |
{ | |
Write(ex); | |
Console.WriteLine("Log file output."); | |
Console.ReadKey(); | |
} | |
} | |
private static void Write(Exception ex) | |
{ | |
var sb = new StringBuilder(); | |
sb.Length = 0; | |
sb.AppendFormat("発生時刻:{0}\n", DateTime.Now); | |
sb.AppendFormat("発生箇所:{0}\n", ex.TargetSite); | |
sb.AppendFormat("例外タイプ:{0}\n", ex.GetType().Name); | |
sb.AppendFormat("内容 :{0}\n", ex.Message); | |
sb.AppendLine("スタックトレース"); | |
sb.AppendLine(ex.StackTrace); | |
string path = Path.Combine(Program._filePath + DateTime.Now.ToString("yyyyMMdd") + "ExceptionLog.log"); | |
using (var stream = new StreamWriter(path, true, Program._encode)) | |
{ | |
try | |
{ | |
stream.Write(sb.ToString()); | |
} | |
finally | |
{ | |
stream.Close(); | |
} | |
} | |
} | |
private static void Func() | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment