1
0
Fork 0

Logger Add Outputs

This commit is contained in:
sheychen 2017-01-20 14:58:41 +01:00
parent f7880dd6e0
commit b46e11e2c6
1 changed files with 203 additions and 163 deletions

View File

@ -8,190 +8,230 @@ using System.Threading;
namespace MyCommon namespace MyCommon
{ {
public class Logger public class Logger
{ {
public enum logType { dev = 0, debug, info, warm, error, fatal } public enum logType { dev = 0, debug, info, warm, error, fatal }
public enum logConsole { normal, show, hide } public enum logDisplay { normal, show, hide }
public struct Log public struct Log
{ {
public string text; public string text;
public logType type; public logType type;
public logConsole console; public logDisplay display;
public Log(string p1, logType p2, logConsole p3 = logConsole.normal) public Log(string p1, logType p2, logDisplay p3 = logDisplay.normal)
{ {
text = p1; text = p1;
type = p2; type = p2;
console = p3; display = p3;
} }
} }
private List<Log> toWriteLogs = new List<Log>(); List<Log> toWriteLogs = new List<Log>();
private string logPath; string logPath;
private ConsoleColor[] logBackColor; ConsoleColor[] logBackColor;
private ConsoleColor[] logForeColor; ConsoleColor[] logForeColor;
private Thread Updater; Thread Updater;
private logType logLevel = logType.info; logType logLevel = logType.info;
private bool _run = true; bool _run = true;
public bool run { get { return _run; } } public bool run { get { return _run; } }
private static bool _debug = false; static bool _debug = false;
private static bool _dev = false; static bool _dev = false;
public enum ConsoleTypes { Any, System, IO }; List<string> _outList;
private ConsoleTypes consoleType = ConsoleTypes.Any; public List<string> outList { get { return _outList; } }
/// <summary> string _outText;
/// Create log file and start logger thread public string outText { get { return _outText; } }
/// </summary>
/// <param name="LogPath">Absolute path to logs directory</param>
public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel, bool debug, bool dev, ConsoleTypes consoletype = ConsoleTypes.Any)
{
consoleType = consoletype;
logPath = LogPath;
logBackColor = backColor;
logForeColor = foreColor;
logLevel = LogLevel;
_debug = debug;
_dev = dev;
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
Write("Log Directory Created", logType.info);
}
else
{
//Sort old logs
string[] files = Directory.GetFiles(logPath);
foreach (string file in files) public struct Outputs
{ {
if (Path.GetExtension(file) == ".log") public bool File;
{ public bool Console;
string name = Path.GetFileName(file); public bool ConsoleIO;
name = name.Substring(0, Math.Min(name.Length, 10)); public bool List;
if (name.Length == 10) public bool Text;
{
if (name != DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
{
int y;
int m;
int d;
if (int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d)) public Outputs(bool file = true, bool console = false, bool consoleIO = true, bool stringList = false, bool text = false )
{ {
if (!Directory.Exists(logPath + "/" + y + "/" + m + "/" + d)) File = file;
{ Console = console;
Directory.CreateDirectory(logPath + "/" + y + "/" + m + "/" + d); ConsoleIO = consoleIO;
} List = stringList;
File.Move(file, logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file)); Text = text;
} }
} }
}
}
}
}
if (consoleType != ConsoleTypes.Any) Outputs outputs;
/// <summary>
/// Create log file and start logger thread
/// </summary>
/// <param name="LogPath">Absolute path to logs directory</param>
public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel = logType.info, bool debug = false, bool dev = false, Outputs output = new Outputs())
{
outputs = output;
logPath = LogPath;
logBackColor = backColor;
logForeColor = foreColor;
logLevel = LogLevel;
_debug = debug;
_dev = dev;
if (outputs.File)
{
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
Write("Log Directory Created", logType.info);
}
else
{
//Sort old logs
string[] files = Directory.GetFiles(logPath);
foreach (string file in files)
{
if (Path.GetExtension(file) == ".log")
{
string name = Path.GetFileName(file);
name = name.Substring(0, Math.Min(name.Length, 10));
if (name.Length == 10)
{
if (name != DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
{
int y;
int m;
int d;
if (int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d))
{
if (!Directory.Exists(logPath + "/" + y + "/" + m + "/" + d))
{
Directory.CreateDirectory(logPath + "/" + y + "/" + m + "/" + d);
}
File.Move(file, logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file));
}
}
}
}
}
}
int i = 0;
while (File.Exists(logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; }
logPath = logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log";
Write("Log path:" + logPath, logType.debug);
}
if (outputs.Console || outputs.ConsoleIO)
{ {
Console.BackgroundColor = logBackColor[0]; Console.BackgroundColor = logBackColor[0];
Console.ForegroundColor = logForeColor[0]; Console.ForegroundColor = logForeColor[0];
Console.Clear(); Console.Clear();
} }
int i = 0; if (outputs.Text)
while (File.Exists(logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } {
logPath = logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log"; _outText = "";
Write("Log path:" + logPath, logType.debug); }
Updater = new Thread(new ThreadStart(UpdaterLoop));
Updater.Start();
}
public void Join() if (outputs.List)
{ {
_run = false; _outList = new List<string>();
Updater.Join(); }
Updater = new Thread(new ThreadStart(UpdaterLoop));
Updater.Start();
} }
public void ChangeLevel(logType level) public void Join()
{ {
logLevel = level; _run = false;
Write("Change to " + logLevel.ToString(), logType.info, logConsole.show); Updater.Join();
} }
/// <summary> public void ChangeLevel(logType level)
/// Add log to log pile {
/// </summary> logLevel = level;
/// <param name="text">Log text</param> Write("Change to " + logLevel, logType.info, logDisplay.show);
/// <param name="type">Log status</param> }
/// <param name="console">Server display modifier</param>
public void Write(string text, logType type, logConsole console = logConsole.normal)
{
Write(new Log(text, type, console));
}
/// <summary> /// <summary>
/// Add log to log pile /// Add log to log pile
/// </summary> /// </summary>
/// <param name="log">Log struct</param> /// <param name="text">Log text</param>
private void Write(Log log) /// <param name="type">Log status</param>
{ /// <param name="console">Server display modifier</param>
if (_debug || _dev) public void Write(string text, logType type, logDisplay console = logDisplay.normal)
{ {
//Add Source Method Write(new Log(text, type, console));
log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; }
}
toWriteLogs.Add(log);
}
/// <summary> /// <summary>
/// Write log pile to logfile and console /// Add log to log pile
/// </summary> /// </summary>
public void UpdaterLoop() /// <param name="log">Log struct</param>
{ void Write(Log log)
while (_run || toWriteLogs.Count > 0) {
{ if (_debug || _dev)
while (toWriteLogs.Count > 0)
{
Log log = toWriteLogs[0]; //Saved log -> any lock need
if (log.type >= logLevel)
{
File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine);
if (log.console != logConsole.hide)
{
ConsoleWrite(log);
}
}
else
{
if (log.console == logConsole.show)
{
ConsoleWrite(log);
}
}
toWriteLogs.Remove(log);
}
}
}
private void ConsoleWrite(Log log)
{
string text = DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text;
switch (consoleType)
{ {
case ConsoleTypes.System: //Add Source Method
Console.ResetColor(); log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text;
Console.ForegroundColor = logForeColor[(int)log.type];
Console.BackgroundColor = logBackColor[(int)log.type];
Console.WriteLine(text);
break;
case ConsoleTypes.IO:
ConsoleIO.Write(new ColorStrings(new ColorString(text, logForeColor[(int)log.type], logBackColor[(int)log.type])));
break;
} }
} toWriteLogs.Add(log);
} }
/// <summary>
/// Write log pile to logfile and console
/// </summary>
public void UpdaterLoop()
{
while (_run || toWriteLogs.Count > 0)
{
while (toWriteLogs.Count > 0)
{
Log log = toWriteLogs[0]; //Saved log -> any lock need
if (log.type >= logLevel || log.display == logDisplay.show)
{
string datetime = DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture);
string text = datetime + " [" + log.type.ToString().ToUpper() + "]: " + log.text;
string textfull = datetime + ": " + log.text;
if (outputs.File && log.type >= logLevel)
{
File.AppendAllText(logPath, textfull + Environment.NewLine);
}
if (outputs.Console)
{
Console.ResetColor();
Console.ForegroundColor = logForeColor[(int)log.type];
Console.BackgroundColor = logBackColor[(int)log.type];
Console.WriteLine(text);
}
if (outputs.ConsoleIO)
{
ConsoleIO.Write(new ColorStrings(new ColorString(text, logForeColor[(int)log.type], logBackColor[(int)log.type])));
}
if (outputs.List)
{
_outList.Add(textfull);
}
if (outputs.Text)
{
_outText += textfull + Environment.NewLine;
}
}
toWriteLogs.Remove(log);
}
}
}
}
} }