Created
November 28, 2013 07:35
-
-
Save Baudin999/7688452 to your computer and use it in GitHub Desktop.
A Simple logger for a Windows Service
This file contains 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.IO; | |
using System.Web; | |
namespace test01 | |
{ | |
public static class Logger | |
{ | |
public static void Log(string message) | |
{ | |
try | |
{ | |
string commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); | |
string fileName = string.Format("log_{0}{1}{2}.txt", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year); | |
DateTime now = DateTime.Now; | |
FileInfo fInfo = new FileInfo(commonAppData + "\\" + fileName); | |
using (TextWriter writer = fInfo.AppendText()) | |
{ | |
writer.WriteLine(string.Format("{0}: {1}", now, message)); | |
writer.Flush(); | |
} | |
} | |
catch | |
{ | |
} | |
} | |
public static void Log(Exception ex, string message = "") | |
{ | |
try | |
{ | |
string commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); | |
string fileName = string.Format("log_error_{0}{1}{2}.txt", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year); | |
DateTime now = DateTime.Now; | |
FileInfo fInfo = new FileInfo(commonAppData + "\\" + fileName); | |
using (TextWriter writer = fInfo.AppendText()) | |
{ | |
writer.WriteLine(); | |
if (!string.IsNullOrWhiteSpace(message)) | |
{ | |
writer.WriteLine(string.Format("{0} MESSAGE: {1}", now, message)); | |
} | |
writer.WriteLine(string.Format("{0} ERROR: {1}", now, ex.Message)); | |
writer.WriteLine(string.Format(ex.StackTrace)); | |
while (ex.InnerException != null) | |
{ | |
writer.WriteLine(ex.InnerException.Message); | |
writer.WriteLine(string.Format(ex.InnerException.StackTrace)); | |
ex = ex.InnerException; | |
} | |
writer.WriteLine(); | |
writer.Flush(); | |
} | |
} | |
catch | |
{ | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment