Last active
April 13, 2016 15:16
-
-
Save nhobi/ba38aca6a544b39b26310c3e39388ded to your computer and use it in GitHub Desktop.
Dead simple C# logging without config file dependency.
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; | |
public class Logger | |
{ | |
private string LogFilePath { get; set; } | |
private string FileExtension { get; set; } | |
private string FilePrefix { get; set; } | |
public Logger(string path, string filePrefix = "Log", string fileExtension = ".txt") | |
{ | |
LogFilePath = path; | |
FilePrefix = filePrefix; | |
FileExtension = fileExtension; | |
} | |
public void Info(string message) | |
{ | |
Write(string.Format("[INFO] {0}", message)); | |
} | |
public void Warning(string message) | |
{ | |
Write(string.Format("[WARNING] {0}", message)); | |
} | |
public void Error(string message) | |
{ | |
Write(string.Format("[ERROR] {0}", message)); | |
} | |
public void NewLine() | |
{ | |
Write(string.Empty, false); | |
} | |
private void Write(string message, bool usePrefix = true) | |
{ | |
string formattedMessage = string.Format("<{0}> {1}", DateTime.Now.ToString("HH:mm:ss"), message); | |
string filePath = string.Format("{0}{1}-{2}{3}", LogFilePath, FilePrefix, DateTime.Today.ToString("MM-dd-yyyy"), FileExtension); | |
if(!usePrefix) | |
{ | |
formattedMessage = message; | |
} | |
FileInfo fileInfo = new FileInfo(filePath); | |
fileInfo.Directory.Create(); | |
using (TextWriter textWriter = File.AppendText(filePath)) | |
{ | |
textWriter.WriteLine(formattedMessage); | |
textWriter.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment