1: using System;
2: using System.Diagnostics;
3: using System.IO;
4:
5: namespace HHPS.CreditEducation.Frameworks.Commons
6: {
7: public class Logger
8: {
9: public const string LOG_FILE_NAME = "log.txt";
10:
11: public static void Write(string message = null, Exception exception = null)
12: {
13: string content = Environment.NewLine + DateTime.Now + " " +
14: new StackTrace().GetFrame(1).GetMethod() + Environment.NewLine;
15:
16: if (!string.IsNullOrEmpty(message))
17: {
18: content += message + Environment.NewLine;
19: }
20:
21: if (exception != null)
22: {
23: content += exception.Message + Environment.NewLine;
24: content += exception.StackTrace + Environment.NewLine;
25: }
26:
27: File.AppendAllText(Path.Combine(Environment.CurrentDirectory, LOG_FILE_NAME), content);
28: }
29: }
30: }
Log file will write current date time and name of parent method call it by this code:
1: string content = Environment.NewLine + DateTime.Now + " " +
2: new StackTrace().GetFrame(1).GetMethod() + Environment.NewLine;
With a exception, log file write exception message and exception stack trace, very helpful to find bug.
When we use it in other class, we call like this:
1: try
2: {
3: }
4: catch (Exception ex)
5: {
6: Logger.Write(null, ex);
7: }
Enjoy it!