128 lines
3.4 KiB
C#
128 lines
3.4 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace HRM_MQ_Consumer_Service.Logger
|
|
{
|
|
public enum LogLevel
|
|
{
|
|
Info,
|
|
Warning,
|
|
Error
|
|
}
|
|
|
|
public class Logger
|
|
{
|
|
//private readonly string _name;
|
|
//private readonly string _logDirPath;
|
|
|
|
public Logger(string name, string logDirPath = "log\\")
|
|
{
|
|
_name = name;
|
|
_directoryPath = logDirPath;
|
|
|
|
if (!Directory.Exists(logDirPath))
|
|
{
|
|
Directory.CreateDirectory(logDirPath);
|
|
}
|
|
// Ensure the log file exists or create it
|
|
//if (!File.Exists(_logFilePath))
|
|
//{
|
|
// using (File.Create(_logFilePath)) { }
|
|
//}
|
|
}
|
|
|
|
private string _name;
|
|
|
|
public string Name
|
|
{
|
|
get { return _name; }
|
|
set { _name = value; }
|
|
}
|
|
|
|
|
|
private string _directoryPath;
|
|
|
|
public string DirectoryPath
|
|
{
|
|
get { return _directoryPath; }
|
|
set { _directoryPath = value; }
|
|
}
|
|
|
|
public void Log(LogLevel level, string message)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes(message);
|
|
var str = Encoding.UTF8.GetString(bytes);
|
|
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
|
var logMessage = $"[{timestamp}] [{level}] [{_name}] {str}";
|
|
|
|
// Write to console (optional)
|
|
WriteToConsole(level, logMessage);
|
|
|
|
// Write to file
|
|
WriteToFile(logMessage);
|
|
}
|
|
|
|
private void WriteToConsole(LogLevel level, string message)
|
|
{
|
|
switch (level)
|
|
{
|
|
case LogLevel.Info:
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
break;
|
|
case LogLevel.Warning:
|
|
Console.ForegroundColor = ConsoleColor.Yellow;
|
|
break;
|
|
case LogLevel.Error:
|
|
Console.ForegroundColor = ConsoleColor.Red;
|
|
break;
|
|
default:
|
|
Console.ResetColor();
|
|
break;
|
|
}
|
|
|
|
Console.WriteLine(message);
|
|
Console.ResetColor();
|
|
}
|
|
|
|
private void WriteToFile(string message)
|
|
{
|
|
var today = DateTime.Now.ToString("yyyy-MM-dd");
|
|
var filePath = $"{_directoryPath}\\{today}_{_name}.txt";
|
|
if (!File.Exists(filePath))
|
|
{
|
|
using (File.Create(filePath)) { }
|
|
}
|
|
try
|
|
{
|
|
// Append the log message to the file
|
|
using (StreamWriter writer = new StreamWriter(filePath, true, Encoding.UTF8))
|
|
{
|
|
writer.WriteLine(message);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.ForegroundColor = ConsoleColor.Red;
|
|
Console.WriteLine($"Failed to write to log file: {ex.Message}");
|
|
Console.ResetColor();
|
|
}
|
|
}
|
|
|
|
public void Info(string message)
|
|
{
|
|
Log(LogLevel.Info, message);
|
|
}
|
|
|
|
public void Warn(string message)
|
|
{
|
|
Log(LogLevel.Warning, message);
|
|
}
|
|
|
|
public void Error(string message)
|
|
{
|
|
Log(LogLevel.Error, message);
|
|
}
|
|
}
|
|
}
|