Sep 15, 2015

Creating a custom class in C# for creating a log file

Code for the class to create log file:

public class LogUtility : IDisposable
{
public string LogFilePath { get; private set; }
public Level LogLevel { get; private set; }
private FileStream _fs = null;
/// <summary>
/// Constructor
/// </summary>
/// <param name="directoryPath">Folder location for log file</param>
/// <param name="fileName">File Name (date will be automatically added to file name)</param>
/// <param name="logLevel">Default log level to add in log file</param>
public LogUtility(string directoryPath, string fileName, Level logLevel)
{
LogLevel = logLevel;
LogFilePath = (directoryPath.EndsWith(@"\") ? directoryPath : $"{directoryPath}\\") +
$"{fileName}-{DateTime.Today.ToString("yyyy-MM-dd")}.log";
if (!File.Exists(LogFilePath)) //No File? Create
{
_fs = File.Create(LogFilePath);
_fs.Close();
}
}
/// <summary>
/// Log will be written if default log level is DEBUG or ALL
/// </summary>
/// <param name="logMessage">Message as string</param>
public void Debug (string logMessage)
{
LogTextFormatter(Level.DEBUG, logMessage);
}
/// <summary>
/// Log will be written if default log level is INFO, DEBUG or ALL
/// </summary>
/// <param name="logMessage">Message as string</param>
public void Info(string logMessage)
{
LogTextFormatter(Level.INFO, logMessage);
}
/// <summary>
/// Log will be written if default log level is WARN, INFO, DEBUG or ALL
/// </summary>
/// <param name="logMessage">Message as string</param>
public void Warn(string logMessage)
{
LogTextFormatter(Level.WARN, logMessage);
}
/// <summary>
/// Log will be written if default log level is ERROR, WARN, INFO, DEBUG or ALL
/// </summary>
/// <param name="logMessage">Message as string</param>
public void Error(string logMessage)
{
LogTextFormatter(Level.ERROR, logMessage);
}
/// <summary>
/// Log will be written if level is equal or higher than default log level
/// </summary>
/// <param name="level">Log Level</param>
/// <param name="logMessage">Message as string</param>
public void Write(Level level, string logMessage)
{
LogTextFormatter(level, logMessage);
}
/// <summary>
/// Formats the log before adding it to text file
/// </summary>
/// <param name="level">Log Level</param>
/// <param name="logMessage">Message as string</param>
private void LogTextFormatter(Level level, string logMessage)
{
if (LogLevel >= level)
{
File.AppendAllText(LogFilePath,
$"\r\n{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss,fff tt")} : {level.ToString()} : - {logMessage}");
}
}
public void Dispose()
{
if (_fs != null)
_fs.Dispose();
LogFilePath = null;
}
}
public enum Level
{
ERROR, WARN, INFO, DEBUG, ALL
}
view raw LogUtility.cs hosted with ❤ by GitHub

No comments: