-
-
Save Konard/5394500 to your computer and use it in GitHub Desktop.
Log is a class that allowes easy logging to files.
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.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
namespace Konard.Helpers | |
{ | |
public class Log : IDisposable | |
{ | |
public const string DateTimeFormat = "dd.MM.yyyy HH:mm:ss.fff"; | |
#region Structure | |
private bool disposed; | |
private readonly string filename; | |
private readonly FileStream file; | |
private readonly StreamWriter writer; | |
#endregion | |
#region Logic | |
public Log(string filename) | |
{ | |
this.filename = filename; | |
this.file = File.Open(filename, FileMode.Append, FileAccess.Write); | |
this.writer = new StreamWriter(this.file); | |
} | |
public void Message(string message) | |
{ | |
string fullMessage = string.Format("{0:" + Log.DateTimeFormat + "} Message: {1}", DateTime.UtcNow, message); | |
#if DEBUG | |
Console.WriteLine("[DEBUG] " + fullMessage); | |
#endif | |
writer.WriteLine(fullMessage); | |
} | |
public void Error(string error) | |
{ | |
string fullMessage = string.Format("{0:" + Log.DateTimeFormat + "} Error: {1}", DateTime.UtcNow, error); | |
#if DEBUG | |
Console.WriteLine("[DEBUG] " + fullMessage); | |
#endif | |
writer.WriteLine(fullMessage); | |
} | |
#endregion | |
#region Finalizers | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (!disposed) | |
{ | |
if (disposing) | |
{ | |
// unsafe disposing here? | |
} | |
this.writer.Dispose(); | |
this.file.Dispose(); | |
disposed = true; | |
} | |
} | |
~Log() | |
{ | |
Dispose(false); | |
} | |
private void OnProcessExit(object sender, EventArgs e) | |
{ | |
Dispose(); | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment