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

76 lines
2.3 KiB
C#

namespace OMS.NET.Common
{
public class Log
{
private static readonly int _logLevel = 3; //debug
private static int logCount = 0;
private static string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log", $"{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.log");
private static readonly object LogLock = new();
private static void WriteLogToFile(string message)
{
lock (LogLock)
{
using var writer = new StreamWriter(logPath, true);
writer.WriteLine(message);
}
}
private static 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 static void Go(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);
WriteLogToFile(logtext);
logCount++;
}
}
public static void Error(string message)
{
Go(message, 0);
}
public static void Warn(string message)
{
Go(message, 1);
}
public static void Info(string message)
{
Go(message, 2);
}
public static void Debug(string message)
{
Go(message, 3);
}
}
}