という訳で自分の場合はこんな感じでスタック情報からファイル名と行番号を取得して出力してます。
ソースはC#ですよ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
using System; using System.Text; using System.IO; using System.Diagnostics; namespace TestApp { class Program { class Logfunc { private string LogPath = ".\\"; private StreamWriter writer = null; public void LogPut(StackFrame CallStack, string msg) { try { string myname = CallStack.GetFileName(); int myline = CallStack.GetFileLineNumber(); Encoding enc = Encoding.GetEncoding("Shift_JIS"); DateTime dt = DateTime.Now; string fnamedt = dt.ToString("yyyyMMdd"); string fpath = LogPath + "hoge_" + fnamedt + ".log"; using (writer = new StreamWriter(fpath, true, enc)) { string result = dt.ToString("yyyy/MM/dd HH:mm:ss"); writer.WriteLine(result + "\t" + myname + "\t" + myline.ToString() + "\t" + msg); } } catch (Exception e) { Console.WriteLine(e.Message); } finally { if (writer != null) { writer.Close(); writer = null; } } } } static void Main(string[] args) { Logfunc lf = new Logfunc(); lf.LogPut(new StackFrame(0, true), "TEST LINE 1"); lf.LogPut(new StackFrame(0, true), "TEST LINE 2"); lf.LogPut(new StackFrame(0, true), "TEST LINE 3"); lf.LogPut(new StackFrame(0, true), "TEST LINE 4"); } } } |
※かなり強引に書いたサンプルなのでノリだけ見ていただければ。
StackFramについてはマイクロソフトサイトで見てくださいね。
StackFram引数の一番目はスタックの階層表してるので何某かのエラーが発生して現在ではなく直前の状態が欲しい場合は0ではなくて1とかになりますね。
一度色々試すと意味がわかるかと思います。