Previous question: C# Logging System
I have took your answers on board and added the following changes to my LogManager.cs class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sahara.Sahara.Core.Logging
{
class LogManager
{
/// <summary>
/// Holds the logging settings class.
/// </summary>
private readonly LogSettings logSettings;
public LogManager()
{
this.logSettings = new LogSettings
{
TypesToSave = new List<LogType>(),
LogFile = "Logs/line_logs.txt"
};
}
/// <summary>
/// Prints a line to the console using custom settings.
/// </summary>
/// <param name="line">Line you want to print.</param>
/// <param name="logType">Type of line you want to print.</param>
public void Log(string line, LogType logType)
{
ConsoleColor existingColor = Console.ForegroundColor;
PrintLine(line);
Console.ForegroundColor = existingColor;
if (logSettings.TypesToSave.Contains(logType))
WriteContentToFile(logSettings.LogFile, line);
}
/// <summary>
/// Prints a line to the console.
/// </summary>
/// <param name="line">Line to print to the console.</param>
private void PrintLine(string line)
{
Console.WriteLine(GetLogDateTime() + line);
}
/// <summary>
/// Retruns a short string with the current time in brackets
/// </summary>
/// <returns></returns>
private string GetLogDateTime()
{
return "[" + DateTime.Now.ToLongTimeString() + "] ";
}
/// <summary>
/// Adds text to the log file.
/// </summary>
/// <param name="filePath">The path of the log file.</param>
/// <param name="content">The text to write in the file.</param>
private void WriteContentToFile(string filePath, string content)
{
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read))
using (StreamWriter writer = new StreamWriter(fileStream, Encoding.Unicode))
{
writer.Write(content);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
}