You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

101 lines
3.0 KiB

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CDPShared
{
public class MinLogging
{
public string LoggerName = string.Empty;
static string LogFile = @"CircleViewer.txt";
static MinLogging()
{
try
{
LogFile = Path.Combine(Constants.CircleFolder, LogFile);
if (File.Exists(LogFile))
{
System.IO.FileInfo fi = new System.IO.FileInfo(LogFile);
if (fi.Length > 10000000) // don't let the log file get larger than 10MB
{
try
{
File.Delete(LogFile);
}
catch (Exception e)
{
Trace.WriteLine(e);
}
}
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
public static void LogIt(string str)
{
try
{
// only log to file if THIS is the same or higher level of detail as my desired logging level
str = string.Format("{0}|{1}|{2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, str);
lock (LogFile)
{
File.AppendAllText(LogFile, str + Environment.NewLine);
if (str.Length < 512)
{
byte[] data = Encoding.ASCII.GetBytes(str);
}
else
{
byte[] data = Encoding.ASCII.GetBytes(string.Format($"String to long. Length: {str.Length}"));
}
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
}
public class LogMethod : IDisposable
{
private string _methodName;
private Stopwatch _sw;
/// <summary>
/// Ctor now private - just called from the static Log method
/// </summary>
/// <param name="methodName">The name of the method being logged</param>
private LogMethod(string methodName)
{
_methodName = methodName;
_sw = new Stopwatch();
_sw.Start();
string msg = string.Format(">> Entering {0}", _methodName);
MinLogging.LogIt(msg);
}
/// <summary>
/// Tidy up
/// </summary>
public void Dispose()
{
_sw.Stop();
string msg = string.Format("<< Exiting {0}: elapsed Time: {1} ms", _methodName, _sw.ElapsedMilliseconds);
MinLogging.LogIt(msg);
}
public static IDisposable Log(string callingMethodTypeHardcode)
{
return new LogMethod(callingMethodTypeHardcode);
}
}
}