Last active
October 24, 2024 15:23
-
-
Save mikey-t/7999228 to your computer and use it in GitHub Desktop.
Simple C# utility class to output to both console and a log file at the same time. Use it by simply calling Output.Write() and Output.WriteLine().
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
public class Output | |
{ | |
private readonly string LogDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs"); | |
private static Output _outputSingleton; | |
private static Output OutputSingleton | |
{ | |
get | |
{ | |
if (_outputSingleton == null) | |
{ | |
_outputSingleton = new Output(); | |
} | |
return _outputSingleton; | |
} | |
} | |
public StreamWriter SW { get; set; } | |
public Output() | |
{ | |
EnsureLogDirectoryExists(); | |
InstantiateStreamWriter(); | |
} | |
~Output() | |
{ | |
if (SW != null) | |
{ | |
try | |
{ | |
SW.Dispose(); | |
} | |
catch(ObjectDisposedException){} // object already disposed - ignore exception | |
} | |
} | |
public static void WriteLine(string str) | |
{ | |
Console.WriteLine(str); | |
OutputSingleton.SW.WriteLine(str); | |
} | |
public static void Write(string str) | |
{ | |
Console.Write(str); | |
OutputSingleton.SW.Write(str); | |
} | |
private void InstantiateStreamWriter() | |
{ | |
string filePath = Path.Combine(LogDirPath, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")) + ".txt"; | |
try | |
{ | |
SW = new StreamWriter(filePath); | |
SW.AutoFlush = true; | |
} | |
catch (UnauthorizedAccessException ex) | |
{ | |
throw new ApplicationException(string.Format("Access denied. Could not instantiate StreamWriter using path: {0}.", filePath), ex); | |
} | |
} | |
private void EnsureLogDirectoryExists() | |
{ | |
if (!Directory.Exists(LogDirPath)) | |
{ | |
try | |
{ | |
Directory.CreateDirectory(LogDirPath); | |
} | |
catch (UnauthorizedAccessException ex) | |
{ | |
throw new ApplicationException(string.Format("Access denied. Could not create log directory using path: {0}.", LogDirPath), ex); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for sharing this!