Skip to content

Instantly share code, notes, and snippets.

@mikey-t
Last active April 5, 2024 13:21
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save mikey-t/7999228 to your computer and use it in GitHub Desktop.
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().
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);
}
}
}
}
@Timmate
Copy link

Timmate commented Jun 30, 2022

Thanks a lot for sharing this!

@AKASGaming
Copy link

AKASGaming commented Aug 29, 2022

Using this in AKASGaming/DigitalHomeCinemaManager, much thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment