You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OMS.NET/Common/Logger.cs

81 lines
2.3 KiB
C#

namespace OMS.NET.Common
{
public class Logger
{
private readonly int _logLevel;
private int logCount;
private string logPath;
private static readonly object LogLock = new();
private void WriteLog(string message)
{
lock (LogLock)
{
using var writer = new StreamWriter(logPath, true);
writer.WriteLine(message);
}
}
public Logger(int level)
{
_logLevel = level;
logPath = GetNewLogFile();
}
private string GetNewLogFile()
{
logCount = 0;
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log", $"{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.log");
if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log")))
{
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"));
}
File.WriteAllText(path, "");
return path;
}
private void Log(string message, int level)
{
if (level <= _logLevel)
{
string logtime = DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]");
string leveltext = level switch
{
0 => "[ERROR]",
1 => "[WARN]",
2 => "[INFO]",
3 => "[DEBUG]",
_ => level.ToString(),
};
string logtext = leveltext + " " + logtime + " " + message;
Console.WriteLine(logtext);
if (logCount > 100000)
{
logPath = GetNewLogFile();
}
//File.AppendAllTextAsync(this.logPath, logtext);
WriteLog(logtext);
logCount++;
}
}
public void Error(string message)
{
Log(message, 0);
}
public void Warn(string message)
{
Log(message, 1);
}
public void Info(string message)
{
Log(message, 2);
}
public void Debug(string message)
{
Log(message, 3);
}
}
}