Skip to content

Instantly share code, notes, and snippets.

@Baudin999
Created November 28, 2013 07:35
Show Gist options
  • Save Baudin999/7688452 to your computer and use it in GitHub Desktop.
Save Baudin999/7688452 to your computer and use it in GitHub Desktop.
A Simple logger for a Windows Service
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